閱讀387 返回首頁    go 阿裏雲 go 技術社區[雲棲]


初始化python類的實例時,私有變量的值與上一個實例的相同,問題定位

#!/usr/bin/env python
# -*- Coding=UTF-8 -*-

class parser:
    def __init__(self, x=[]):
        print "early-init: id(x) = %s" % id(x)
        self.numbers = x
        print "post-init: id(self.numbers) = %s, id(x) = %s" % (id(self.numbers), id(x))
    def load(self):
        for i in range(0, 10):
            self.numbers.append(i)

p = parser()
p.load()
print "len(p.numbers): %s " % len(p.numbers)
p1 = parser()
print "len(p1.numbers): %s " % len(p1.numbers)

 上述代碼的運行結果為:

early-init: id(x) = 4531521656
post-init: id(self.numbers) = 4531521656, id(x) = 4531521656
len(p.numbers): 10
early-init: id(x) = 4531521656
post-init: id(self.numbers) = 4531521656, id(x) = 4531521656
len(p1.numbers): 10

 原因很明顯,__init__的默認輸入參數x的地址是不變的。
如果初始化實例p時,沒有指定參數,那麼將拷貝x的值到p.numbers,修改了p.numbers的內容,也就是修改了x的內容。
初始化p1時,參數沒有指定,使用默認值x,x的內容已經被p.numbers修改,不再是[]。
安全的做法是self.numbers = x[:]。

最後更新:2017-10-26 17:34:19

  上一篇:go  libffi淺析
  下一篇:go  阿裏雲雙11活動擼福利攻略雲市場篇 1.1億紅包賺不停