Global variables within classes.

Duncan Booth duncan.booth at invalid.invalid
Sat Nov 10 09:15:49 EST 2007


Donn Ingle <donn.ingle at gmail.com> wrote:

>> class Stack:
>>     list = []
> Okay, this has me a little weirded-out. How is this different from
> putting it in: 
> def __init__(self):
>         self.list = []
> ?
> I see from tests that it is different, but I don't quite grok it. Who
> owns the list ref?
> 

The first creates an attribute of the class, the second creates an 
attribute in the instance.

When you access an attribute of an instance but the instance does not have 
an attribute with the required name Python looks for the attribute in the 
class instead. So in the first case it would look as though each instance 
has a 'list' attribute, but it is the same value shared between all 
instances. In the second case each instance has its own 'list' attribute.

Actually the lookup is somewhat more complex than that when you use new-
style classes (and you should always use new-style classes): properties (or 
other objects with a 'get' method) are class attributes but take precedence 
over instance attributes.



More information about the Python-list mailing list