Inheritance and Attributes

Graeme Winter g.winter at dl.ac.uk
Thu Feb 13 07:05:10 EST 2003


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

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.

I guess that I could stick all of the data into the class definition 
rather than the constructor, but this would prevent me from passing 
information to the object at creation time.

Any help (in particular an explaination of why this is happening) would 
be appreciated. The books I have don't like to talk too much about this.

Cheers,

Graeme





More information about the Python-list mailing list