473,324 Members | 2,541 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

dumb q: repeated inheritance in python?

Hi, here's a silly question. I'm wrote some code a while back that
looks like this:

import types

class Named(object):
def __init__(self,nm=''):
self.iname = ''
self.setnm(nm)
def setnm (self,nm):
if isinstance(nm, types.StringType):
self.iname = nm
else:
raise TypeError, "Name passed to Named isn't a string."
def getnm (self):
return self.iname
name = property(getnm,setnm)

Pretty basic, a name attribute with simple type checking, it works
fine and the code using it is fine. Well, it was, until I came up
with an object that needed two names, with the same basic type
checking. Now the simplistic way to do that would be copy this class
to another class, say Named2, rename the property name2 and be done
with it. On the other hand, having code that's basically an exact
duplicate of other code except for some name changes seems a tad
inelegant. What I'd really like to do is inherit this same object
twice, but the second time rename the objects so that I get 'name2'
instead of 'name'. (And somehow rename the functions, and so on.)

But I can't figure out how to do it. Is there some way to do this? I
suspect there might be some way to do it with metaclasses, but I
haven't really wrapped my head around that stuff yet. Maybe something
with the new 'super' keyword? Beats me. Anyway, any help would be
great, thanks!!!
Jul 18 '05 #1
3 1490

"Corey Coughlin" <co************@attbi.com> wrote in message
news:a8**************************@posting.google.c om...
Hi, here's a silly question. I'm wrote some code a while back that
looks like this:

import types

class Named(object):
def __init__(self,nm=''):
self.iname = ''
self.setnm(nm)
def setnm (self,nm):
if isinstance(nm, types.StringType):
self.iname = nm
else:
raise TypeError, "Name passed to Named isn't a string."
def getnm (self):
return self.iname
name = property(getnm,setnm)

Pretty basic, a name attribute with simple type checking, it works
fine and the code using it is fine. Well, it was, until I came up
with an object that needed two names, with the same basic type
checking. Now the simplistic way to do that would be copy this class
to another class, say Named2, rename the property name2 and be done
with it. On the other hand, having code that's basically an exact
duplicate of other code except for some name changes seems a tad
inelegant. What I'd really like to do is inherit this same object
twice, but the second time rename the objects so that I get 'name2'
instead of 'name'. (And somehow rename the functions, and so on.)

But I can't figure out how to do it. Is there some way to do this? I
suspect there might be some way to do it with metaclasses, but I
haven't really wrapped my head around that stuff yet. Maybe something
with the new 'super' keyword? Beats me. Anyway, any help would be
great, thanks!!!


Why do the two names have to be in the same object instance? I'd
think the simplest approach would be to bind two instances of your
Named class to two different identifiers.

Otherwise, if you actually need some kind of a collection class, I'd
purpose build one: NamedCollection, or some such.

John Roth
Jul 18 '05 #2
co************@attbi.com (Corey Coughlin) wrote in
news:a8**************************@posting.google.c om:
What I'd really like to do is inherit this same object
twice, but the second time rename the objects so that I get 'name2'
instead of 'name'. (And somehow rename the functions, and so on.)


I'm not sure if I exactly understood what you want, but does this help?
I think you are asking for two properties that access differently named
attributes but perform the same type checking in each case.

That sounds to me like you want a specialised property which can be done by
subclassing it:

---- begin test.py ----
class Name(property):
def __init__(cls, attrname):

def setnm(self, nm):
if isinstance(nm, str):
setattr(self, attrname, nm)
else:
raise TypeError("Name passed to %s isn't a string" %
self.__class__.__name__)

def getnm(self):
return getattr(self, attrname)

property.__init__(cls, getnm, setnm)
class TwoNamed(object):
def __init__(self, iname='', jname=''):
self.iname, self.jname = iname, jname

name = Name('iname')
name2 = Name('jname')

x = TwoNamed('ivalue', 'jvalue')
print "name, name2 =",x.name, x.name2

x.name = 'www'
x.name2 = 'xxx'

print "name, name2 =",x.name, x.name2
print "iname, jname =",x.iname, x.jname

x.name = 42 # Blows up
print x.name # Never reached.
----- end of test.py ----
--
Duncan Booth du****@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #3
Thanks Duncan, that's exactly what I needed! I'm not very familiar
with subclassing properties, I guess I'll play around with it and see
if I can figure it out. But thanks again, it's great code!

------ Corey
Duncan Booth <du****@NOSPAMrcp.co.uk> wrote in message news:<Xn***************************@127.0.0.1>...
co************@attbi.com (Corey Coughlin) wrote in
news:a8**************************@posting.google.c om:
What I'd really like to do is inherit this same object
twice, but the second time rename the objects so that I get 'name2'
instead of 'name'. (And somehow rename the functions, and so on.)


I'm not sure if I exactly understood what you want, but does this help?
I think you are asking for two properties that access differently named
attributes but perform the same type checking in each case.

That sounds to me like you want a specialised property which can be done by
subclassing it:

---- begin test.py ----
class Name(property):
def __init__(cls, attrname):

def setnm(self, nm):
if isinstance(nm, str):
setattr(self, attrname, nm)
else:
raise TypeError("Name passed to %s isn't a string" %
self.__class__.__name__)

def getnm(self):
return getattr(self, attrname)

property.__init__(cls, getnm, setnm)
class TwoNamed(object):
def __init__(self, iname='', jname=''):
self.iname, self.jname = iname, jname

name = Name('iname')
name2 = Name('jname')

x = TwoNamed('ivalue', 'jvalue')
print "name, name2 =",x.name, x.name2

x.name = 'www'
x.name2 = 'xxx'

print "name, name2 =",x.name, x.name2
print "iname, jname =",x.iname, x.jname

x.name = 42 # Blows up
print x.name # Never reached.
----- end of test.py ----

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Hung Jung Lu | last post by:
Hi, I think Microsoft did look into Python when they designed C#. (E.g. they got rid of checked exceptions of Java.) However, they followed Java in avoiding multiple inheritance (MI), which is a...
4
by: Dan Bullok | last post by:
I have a couple of classes: class Base: ... class Sub(Base): ... I want to subclass Base and Sub, i.e. define classes: class MyBase(Base):
6
by: Brian Jones | last post by:
I'm sure the solution may be obvious, but this problem is driving me mad. The following is my code: class a(object): mastervar = def __init__(self): print 'called a'
2
by: AIM | last post by:
Error in msvc in building inheritance.obj to build hello.pyd Hello, I am trying to build the boost 1.31.0 sample extension hello.cpp. I can not compile the file inheritance.cpp because the two...
13
by: John Perks and Sarah Mount | last post by:
Trying to create the "lopsided diamond" inheritance below: >>> class B(object):pass >>> class D1(B):pass >>> class D2(D1):pass >>> class D(D1, D2):pass Traceback (most recent call last): File...
20
by: km | last post by:
Hi all, In the following code why am i not able to access class A's object attribute - 'a' ? I wishto extent class D with all the attributes of its base classes. how do i do that ? thanks in...
0
by: Terry Hancock | last post by:
I've been discussing PyProtocols with a a friend collaborating with me on a SF game project, about the benefits and design concept of "component architecture", and I'm a little confused by what...
16
by: devicerandom | last post by:
Hi, I am currently using the Cmd module for a mixed cli+gui application. I am starting to refactor my code and it would be highly desirable if many commands could be built as simple plugins. ...
18
by: GD | last post by:
Please remove ability to multiple inheritance in Python 3000. Multiple inheritance is bad for design, rarely used and contains many problems for usual users. Every program can be designed only...
10
by: Aaron Gray | last post by:
Wikipedia says Python has Multiple Inheritance, is this true ? http://en.wikipedia.org/wiki/Multiple_inheritance Thanks, Aaron
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.