Is a list static when it's a class member?
Ben Finney
bignose+hates-spam at benfinney.id.au
Tue Oct 10 20:26:50 EDT 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 class.
> 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
object.
> 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):
> self.data.append(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 |
_o__) |
Ben Finney
More information about the Python-list
mailing list