开发者

Python - Why is this happening?

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 e开发者_如何学运维xecuted 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 test class share the same dictionary and list. The correct way to initialize the members would be:

class Test():
    def __init__(self):
        self.dictionary1 = {}
        self.list1 = []

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.


Variables directly declared in the class body (static class variables) are shared among all instances of the class. Therefore, it's not a good idea to change them.

Instead, initialize object member variables in the constructor:

class test(object):
    def __init__(self):
        self.dictionary1 = {}
    def method1(self):
        self.dictionary1.update({'1': 'unique entry'})


To add to the other answers, the reason you see different behaviour for the dict and the list is: when you write self.dictionary1.update({'1': 'unique entry'}), you change the contents of self.dictionary1, but it's still the same dict object. When you write self.list1 = ['unique list entry'], you replace self.list1 with a new list object. You would get the same behaviour as with the dict by doing: self.list1.append('unique list entry').

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜