简体   繁体   English

断言如何影响Python中的变量分配?

[英]How does assertion affect variable assignment in Python?

I am having some sort of issue with list aliasing or variable assignment in Python 2.7. 我在Python 2.7中遇到列表别名或变量赋值的问题。 I will show you a minimal example. 我将向您展示一个简单的例子。 There are two different results with and without the assertion , and I don't know why/how the assertion affects this. 断言和没有断言两种不同的结果 ,我不知道断言为什么/如何影响这一点。

Somehow it is overwriting an attribute when I append something to the object_list shown below: 当我向如下所示的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

Here is a minimal example: 这是一个最小的示例:

With the assertion 有了断言

mfd = Object1()
myAgent = Thing('blah')
myAgent_2 = Thing('blew')

mfd.add_thing(myAgent)
mfd.add_thing(myAgent_2)

print mfd.object_list

>> [blah, blah]

Without the assertion 没有断言

mfd = Object1()
myAgent = Thing('blah')
myAgent_2 = Thing('blew')

mfd.add_thing(myAgent)
mfd.add_thing(myAgent_2)

print mfd.object_list

>> [blah, blew]

Can someone please explain to me how the assertion above is affecting this? 有人可以向我解释上面的断言如何影响这一点吗? Thank you. 谢谢。

In python 2, implicit assignments made in the scope of a list comprehension leak outside of the comprehension to the caller's scope. 在python 2中,在列表理解范围内进行的隐式赋值泄漏到对调用者范围的理解之外。

So in your example, by executing the assert, thing 's value changes and the final value of thing is the final thing from object_list . 因此,在你的榜样,通过执行断言, thing的价值变化和最终值thing是从最后一件事object_list Therefore, without assert , you are appending a different thing than after the assert has been executed. 因此,如果没有assert ,您将添加与执行assert之后不同的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM