__init__ & attributes clarification
Peter Hansen
peter at engcorp.com
Sun Feb 2 17:05:30 EST 2003
Afanasiy wrote:
>
> Are these two, in effect, the same?
>
> class hive:
> workers = []
>
> ...
>
> class hive:
> def __init__(self):
> self.workers = []
Definitely not. Understand that when you define the class,
you are not creating an instance of the class, but just the
"template" for instances (which are called objects).
The __init__ method is used to initialize an *instance* of
a class, which is created when you do "x = hive()". If you
create another instance, "y=hive()", you have two of them,
and each one has its own "workers" list stored inside.
On the other hand, the first example creates a single
workers field which is attached to the *class* itself,
not to a single instance.
Given the names you've used, it seems likely the latter
example is the way you want to go (each hive has its own
workers).
-Peter
More information about the Python-list
mailing list