python 中 dict 在類中宣告的位置不一樣,結果有所差別
阿新 • • 發佈:2018-12-14
- 第一種宣告方式:
class A(object):
names = {}
def output(self):
print(self.names)
class A1(A):
pass
class A2(A):
pass
import time
a1 = A1()
a2 = A2()
a1.names["name"] = "jack"
for i in range(100):
time.sleep(2)
a1.output()
a2.output()
輸出結果如下:
- 第二種方式:
class A(object): def __init__(self): self.names = {} def output(self): print(self.names) class A1(A): pass class A2(A): pass import time a1 = A1() a2 = A2() a1.names["name"] = "jack" for i in range(100): time.sleep(2) a1.output() a2.output()
輸出結果如下: