Inheritance question
Eric Brunel
see.signature at no.spam
Tue Mar 25 12:23:30 EDT 2008
On Tue, 25 Mar 2008 16:37:00 +0100, Brian Lane <bcl at brianlane.com> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Gerard Flanagan wrote:
>
>> Use the child class when calling super:
>>
>> --------------------------------------
>> 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 = super(FooSon, self).getid()
>> b = self.id
>> return '%d.%d' % (a,b)
>>
>> print FooSon().getid()
>> --------------------------------------
>
> That still doesn't do what he's trying to do.
>
> The problem here is that you only have one instance. self refers to it,
> so when you set self.id in the super you have set the instance's id to
> 1. When you set it to 2 after calling the super's __init__ you are now
> setting the *same* variable to a 2.
>
> Basically, you can't do what you are trying to do without using a
> different variable, or keeping track of a separate instance for the
> super instead of sub-classing it.
If for any reason it's better to have the same attribute name, it might be
a case where a "pseudo-private" attribute - i.e. prefixed with __ - can be
handy:
--------------------------------------
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 = super(FooSon, self).getid()
b = self.__id
return '%d.%d' % (a,b)
print FooSon().getid()
--------------------------------------
For an explanation, see here:
http://docs.python.org/ref/atom-identifiers.html
HTH
--
python -c "print ''.join([chr(154 - ord(c)) for c in
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
More information about the Python-list
mailing list