考虑以下 python test.py 模块:
class Container:
def __init__(self, str_list=[]):
self.str_list = str_list
def from_strings(self, st=""):
self.str_list.append(st)
return self
o1 = Container().from_strings(st="o1")
o2 = Container().from_strings(st="o2")
o3 = Container().from_strings(st="o3")
def prnt():
print("o1's list:"+str(o1.str_list))
print("o2's list:"+str(o2.str_list))
print("o3's list:"+str(o3.str_list))
if __name__ == '__main__':
prnt()
为什么输出python test.py
:
o1's list:['o1', 'o2', 'o3']
o2's list:['o1', 'o2', 'o3']
o3's list:['o1', 'o2', 'o3']
代替:
o1's list:['o1']
o2's list:['o2']
o3's list:['o3']
(似乎我错过了为什么同一模块中不同实例的字段(str_list)可能会混淆。一个指向解释这个概念的python文档的指针将不胜感激)