有人能指出我做错了什么或我的理解错误吗?我在做什么错? Python对象实例化保持以前实例化的数据?
对我来说,下面实例化两个对象的代码似乎应该为每个实例化都有单独的数据。
class Node:
def __init__(self, data = []):
self.data = data
def main():
a = Node()
a.data.append('a-data') #only append data to the a instance
b = Node() #shouldn't this be empty?
#a data is as expected
print('number of items in a:', len(a.data))
for item in a.data:
print(item)
#b data includes the data from a
print('number of items in b:', len(b.data))
for item in b.data:
print(item)
if __name__ == '__main__':
main()
然而,第二对象是与从第一数据创建的:
>>>
number of items in a: 1
a-data
number of items in b: 1
a-data
重复更换构造函数的第一行:http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the- mutable-default-argument,和http://stackoverflow.com/questions/2313075/python-default-value-for-a-function,和其他许多人。任何与“可变”和“默认”有关的事情。 – 2010-07-01 21:34:42
谢谢大家的快速解答。在发布问题之前,我努力寻找这个问题,但无法做到。希望这个问题的标题能够帮助其他人从某个不了解该问题是函数定义中的可变对象的人的角度对其进行谷歌搜索。 – KobeJohn 2010-07-01 21:43:44