Inheritance question
Hrvoje Niksic
hniksic at xemacs.org
Tue Mar 25 11:59:21 EDT 2008
Tzury Bar Yochay <Afro.Systems at gmail.com> writes:
> given two classes:
>
> class Foo(object):
> def __init__(self):
> self.id = 1
>
> def getid(self):
> return self.id
>
> class FooSon(Foo):
> def __init__(self):
> Foo.__init__(self)
> self.id = 2
>
> def getid(self):
> a = Foo.getid()
> b = self.id
> return '%d.%d' % (a,b)
Try this:
class Foo(object):
def __init__(self):
self.__id = 1
def getid(self):
return self.__id
class FooSon(Foo):
def __init__(self):
Foo.__init__(self)
self.__id = 2
def getid(self):
a = Foo.getid(self)
b = self.__id
return '%d.%d' % (a,b)
>>> FooSon().getid()
'1.2'
> While my intention is to get 1.2 I get 2.2 I would like to know what
> would be the right way to yield the expected results
Either use the above "private" fields, or emulate them yourself by
renaming self.id to self.foo_id or self.foo_son_id, and exposing those
in the class. Or you can have a class-specific dict in each instance,
and so on.
More information about the Python-list
mailing list