我试图理解,即使在注释中有解释,此代码中错误的原因是什么:
"""
This program is part of an exercise in
Think Python: An Introduction to Software Design
Allen B. Downey
WARNING: this program contains a NASTY bug. I put
it there on purpose as a debugging exercise, but
you DO NOT want to emulate this example!
"""
class Kangaroo(object):
"""a Kangaroo is a marsupial"""
def __init__(self, contents=[]):
"""initialize the pouch contents; the default value is
an empty list"""
self.pouch_contents = contents
def __str__(self):
"""return a string representaion of this Kangaroo and
the contents of the pouch, with one item per line"""
t = [ object.__str__(self) + ' with pouch contents:' ]
for obj in self.pouch_contents:
s = ' ' + object.__str__(obj)
t.append(s)
return '\n'.join(t)
def put_in_pouch(self, item):
"""add a new item to the pouch contents"""
self.pouch_contents.append(item)
kanga = Kangaroo()
roo = Kangaroo()
kanga.put_in_pouch('wallet')
kanga.put_in_pouch('car keys')
kanga.put_in_pouch(roo)
print kanga
# If you run this program as is, it seems to work.
# To see the problem, trying printing roo.
解释报告如下:
但我,因为我是Python(和通用)编程新手,还不了解它。在
谢谢。在
问题是,如果将数组作为默认值放在成员定义中,则对于没有传入数组的类的所有实例,它都是相同的数组。因此,不是每个实例都获得一个新的空数组,而是在所有实例之间共享内容。在
问题是在kangaroo类的init部分使用了一个可变对象-list。这导致问题的原因是可变对象为您提供了对对象的引用,有时当您认为您正在制作对象的新副本时,您只是在对同一对象进行新的引用。解决方案会移动定义,以便每次类初始化时都将其计算为新列表,而不是仅当函数init被定义为kangaroo类的一部分时。在
相关问题 更多 >
编程相关推荐