classes: need for an explanation
Peter Otten
__peter__ at web.de
Thu Jan 18 07:14:07 EST 2007
0k- wrote:
> class Thing(object):
> props = {}
> def __init__(self):
> self.props["text"] = TxtAttr("something important")
>
> t1 = Thing()
> t2 = Thing()
>
> t2.props["text"].value = "another string"
>
> print "t1: %s\nt2: %s" % (t1.props["text"].value,
> t2.props["text"].value)
>
> the above code outputs:
>
> t1: another string
> t2: another string
>
> so the problem i cannot get through is that both t1 and t2 have the
> same attr class instance.
> could somebody please explain me why? :)
Putting an assignment into the class body makes the name a /class/ attribute
which is shared by all instances of the class:
>>> class Thing:
... props = {} # this is a class attribute
...
>>> t1, t2 = Thing(), Thing()
>>> t1.props is t2.props
True
The solution is to move the attribute creation into the initializer:
>>> class Thing:
... def __init__(self):
... self.props = {} # an instance attribute
...
>>> t1, t2 = Thing(), Thing()
>>> t1.props is t2.props
False
Peter
More information about the Python-list
mailing list