Is a list static when it's a class member?
bignose+hates-spam at benfinney.id.au
Wed Oct 11 02:26:50 CEST 2006
"glue" <miracle.glue at gmail.com> writes:
> I have a class with a list member and the list seems to behave like
> it's static while other class members don't.
It's not "static"; rather, it's a class attribute, by virtue of being
bound when the class is defined. Those are shared by all instances of
> The code...
> class A:
> name = ""
> data = 
This runs when the class is defined, creates two new objects and binds
them to the attribute names "name" and "data". All instances will
share both of these unless they re-bind the names to some other
> def __init__(self, name):
> self.name = name
This defines a function that runs on initialisation of a new instance
of the class, and re-binds the attribute name "name" to the object
passed as the second parameter to __init__.
The binding that occurred when the class was defined is now
irrelevant. This is known as "shadowing" the class attribute; you've
re-bound the name to a different object.
> def append(self, info):
This defines a function that runs when the 'append' method is called,
and asks the existing object bound to the "data" attribute -- still
the one that was bound when the class was defined -- to modify itself
in-place (with its own 'append' method).
\ "None can love freedom heartily, but good men; the rest love |
`\ not freedom, but license." -- John Milton |
More information about the Python-list