我对python2.7中的列表别名或变量赋值有一些问题。我给你举个小例子。有和没有断言有两种不同的结果,我不知道断言为什么/如何影响这一点。你知道吗
当我将某些内容附加到object_list
时,不知何故它正在覆盖一个属性,如下所示:
class Object1(object):
def __init__(self):
self.object_list = []
def add_thing(self, thing):
# this next line makes all the difference
assert thing.name not in [thing.name for thing in self.object_list], 'agent id already exists, use another one'
self.object_list.append(thing)
class Thing(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
下面是一个简单的例子:
用断言
mfd = Object1()
myAgent = Thing('blah')
myAgent_2 = Thing('blew')
mfd.add_thing(myAgent)
mfd.add_thing(myAgent_2)
print mfd.object_list
>> [blah, blah]
没有断言
mfd = Object1()
myAgent = Thing('blah')
myAgent_2 = Thing('blew')
mfd.add_thing(myAgent)
mfd.add_thing(myAgent_2)
print mfd.object_list
>> [blah, blew]
有人能给我解释一下上面的断言是如何影响这一点的吗?非常感谢。你知道吗
在Python2中,在列表理解范围内进行的隐式赋值在理解范围之外泄漏到调用者的范围。你知道吗
因此,在您的示例中,通过执行assert,
thing
的值更改,thing
的最终值是来自object_list
的最终值。因此,在没有assert
的情况下,附加的内容与执行assert后不同。你知道吗相关问题 更多 >
编程相关推荐