Inheritance and Attributes
Graeme Winter
g.winter at dl.ac.uk
Thu Feb 13 08:01:51 EST 2003
Alex Martelli wrote:
> Graeme Winter wrote:
>
>
>>Hello All,
>>
>>I will guess that you hear this all the time, but I didn't want to wade
>>through 10k messages to find the answer...
>>
>>Basically, why does this:
>>
>>#!/usr/bin/env python
>>
>>class henry:
>>
>> cat = "green"
>>
>> def __init__(self):
>> self.cat = "yellow"
>> print "setting " + str(self) + ".cat = \"yellow\""
>>
>>class this(henry):
>>
>> def __init__(self):
>> henry.__init__(self)
>>
>>h = this()
>>print this.cat
>>
>>
>>give this:
>>
>>setting <__main__.this instance at 0x8138eec>.cat = "yellow"
>>green
>
>
> Because you're printing the 'cat' attribute from class 'this'
> (which is the same one as from class 'henry', by inheritance),
> *NOT* the same-name attribute from instance 'h'.
>
> Try:
>
> print h.this
>
> and you'll see
>
> yellow
>
> of course.
>
>
>
>>I would expect that since I have called the constructor for my base
>>class, the attribute should exist.... Further, if I remove the cat =
>>"green" line from the class definition I get:
>>
>>setting <__main__.this instance at 0x816465c>.cat = "yellow"
>>Traceback (most recent call last):
>> File "inherit.py", line 15, in ?
>> print this.cat
>>AttributeError: class this has no attribute 'cat'
>>
>>Which I find rather surprising.
>
>
> You find surprising that the class object has no such
> attribute if you've never given it one? You have given
> the INSTANCE an attribute thus named, but what you are
> trying to print is the attribute from the CLASS.
>
>
> Alex
>
Okay, that was dumb. Pilot error there.
More information about the Python-list
mailing list