I am new to Python, and noticed something I believe its a bug.
Edit 2011-09-30:
Forget it. Now I know the attributes created are static and shared between the instances.
Hope this thread helps another python newbies in the same situation as mine.
Consider the following code:
class test():
dictionary1 = {}
list1 = []
def method1(self):
self.dictionary1.update({'1': 'unique entry'})
self.list1 = ['unique list entry']
t=test()
print 'dictionary1 value:', t.dictionary1
print 'list1 value:', t.list1
t.method1()
print 'dictionary1 new value:', t.dictionary1
print 'list1 new value:', t.list1
t2=test()
print 'dictionary1 value:', t2.dictionary1, " -- error -- I just instantiated the class. The correct value would be {}"
print 'list1 value:', t.list1
t2.method1()
print 'dictionary1 new value:', t.dictionary1
print 'list1 new value:', t.list1
Now the question:
Why in line 19 the executed code shows: {'1': 'unique entry'}. I belive it would be: {}
Note that the list has the correct value: [] (empty list in line 20)
Using Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
[GCC 4.4.5] on linux2
Sorry not so good english. From Brazil.
Edit 2011-09-30:
Forget it. Now I know the attributes created are static and shared between the instances.
Hope this thread helps another python newbies in the same situation as mine.
All your instances of
testclass share the same dictionary and list. The correct way to initialize the members would be:Attributes assigned directly in the class body will be evaluated once and then shared between all instances. Since the
__init__method is run once per instance, a new list and dictionary will be created for each instance.