Inheritance and Attributes

Graeme Winter g.winter at
Thu Feb 13 13:05:10 CET 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): = "yellow"
         print "setting " + str(self) + ".cat = \"yellow\""

class this(henry):

     def __init__(self):

h = this()

give this:

setting <__main__.this instance at 0x8138eec>.cat = "yellow"

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 "", line 15, in ?
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.



More information about the Python-list mailing list