Inheritance question
Robert Bossy
Robert.Bossy at jouy.inra.fr
Tue Mar 25 13:01:08 EDT 2008
Hi,
I'm not sure what you're trying to actually achieve, but it seems that
you want an identificator for classes, not for instances. In this case,
setting the id should be kept out of __init__ since it is an instance
initializer: make id static and thus getid() a classmethod.
Furthermore, if you have several Foo subclasses and subsubclasses, etc.
and still want to use the same identificator scheme, the getid() method
would better be defined once for ever in Foo. I propose you the following:
<code>
class Foo(object):
id = 1
def getid(cls):
if cls == Foo: return str(cls.id)
return '%s.%d' % (cls.__bases__[0].getid(), cls.id) # get the
parent id and append its own id
getid = classmethod(getid)
class FooSon(Foo):
id = 2
class Bar(Foo):
id = 3
class Toto(Bar):
id = 1
# Show me that this works
for cls in [Foo, FooSon, Bar, Toto]:
inst = cls()
print '%s id: %s\n also can getid from an instance: %s\n' %
(cls.__name__, cls.getid(), inst.getid())
</code>
One advantage of this approach is that you don't have to redefine the
getid() method for each Foo child and descendent. Unfortunately, the
"cls.__bases__[0]" part makes getid() to work if and only if the first
base class is Foo or a subclass of Foo. You're not using multiple
inheritance, are you?
RB
More information about the Python-list
mailing list