direct initialization of class attributes vs. declarations w/in __init__
Diez B. Roggisch
deets at nospam.web.de
Sun Jun 11 12:09:31 EDT 2006
digitalorganics at gmail.com schrieb:
> What's the difference between initializing class variables within the
> class definition directly versus initializing them within the class's
> __init__ method? Is there a reason, perhaps in certain situations, to
> choose one over the other?
You are confusing class variables with instance variables. The former
are what you can initialize inside the class-statement. However, they
are shared amongst _all_ instances. Consider this little example:
class Foo(object):
FOO = 1
BAR = []
def __init__(self, FOO):
self.FOO = FOO
self.BAR.append(FOO)
def __repr__(self):
return "FOO: %r\nBAR: %r\n" % (self.FOO, self.BAR)
f1 = Foo(1)
print f1
f2 = Foo(2)
print f2
print f1
------
meskal:~/Projects/CameraCalibrator deets$ python2.4 /tmp/test.py
FOO: 1
BAR: [1]
FOO: 2
BAR: [1, 2]
FOO: 1
BAR: [1, 2]
-----
As you can see, the list BAR is shared. And you can also see that
_assigning_ to something like this:
self.FOO
will create an instance-variable. Even if a variable of the same name
existed on the class before!
Which is precisely the difference between using variable initialization
in __init__ and inside the class-statement.
BTW,
self.__class__.FOO = value
will set class-variables inside a method. Just if you wondered.
Diez
More information about the Python-list
mailing list