我是Python的新手,並且發現了一些我相信它的bug。Python - 爲什麼會發生這種情況?
編輯2011-09-30: 忘記它。現在我知道創建的屬性是靜態的並且在實例之間共享。 希望這個線程可以幫助另一個python新手處理和我一樣的情況。
考慮下面的代碼:
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
現在的問題:
爲什麼在19行執行的代碼所示:{'1': 'unique entry'}
。我相信這將是:{}
注意,該列表包含了正確的值:(在第20行空列表)[]
Using Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
[GCC 4.4.5] on linux2
對不起不是那麼好英語。來自巴西。
編輯2011-09-30: 忘記它。現在我知道創建的屬性是靜態的並且在實例之間共享。 希望這個線程可以幫助另一個python新手處理和我一樣的情況。
規則no。 1:錯誤出現在您的代碼中或您對該功能的理解中,而不是在成熟的,經過充分測試的實現中。 – delnan
您的代碼已完全損壞。發佈實際運行的內容。 – Daenyth
'self.list1 = ['唯一列表項']的縮進是否正確?它看起來不在'method1'裏面。 – thegrinner