python - 令人费解的作用域行为

标签 python scope class-members

我似乎无法理解这里发生了什么:

class testclass: 

    def __init__(self): 
        print "new instance" 
    myList=[] 

if __name__ == "__main__":  

    inst1=testclass() 
    inst1.myList.append("wrong") 

    inst2=testclass() 
    inst2.myList.append("behaviour") 

    print "I get the",inst2.myList

输出是:

new instance
new instance
I get the ['wrong', 'behaviour']

我原以为 inst1 中的列表对 inst2 中的列表一无所知,但不知何故它看起来像 myList 的范围超越类的实例化。 我觉得这非常令人不安和困惑,还是我在这里遗漏了什么?

谢谢!

最佳答案

您定义 myList 的方式是一个类属性。

您寻找的行为是对象属性之一:

class testclass:
    def __init__(self): 
        print "new instance"
        self.myList = []

让我们试试看:

>>> t1 = testclass()
new instance
>>> t2 = testclass()
new instance
>>> t1.myList.append(1)
>>> t2.myList.append(2)
>>> t1.myList
[1]
>>> t2.myList
[2]

如果您对类属性感兴趣,请查看 Class documentation .由于 Python 中的类也是对象,就像(几乎)Python 中的所有东西一样,它们可以有自己的属性。

关于python - 令人费解的作用域行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9394428/

相关文章:

python - 在 openerp 版本 6.1 中有 aeroo 报告的错误

python - 条形图中的垂直线

javascript - 作为参数传入的函数 - 访问其他参数?

c++ - 将对象声明为自身的成员变量

python - 在 Django 模板中替代 {% if request.user.is_active %}

python - 是否有任何指南可用于从 Python 2.6 开始编写 Python 以编写将来可轻松迁移到 Python 3 的应用程序?

python - Spark 的 `persist` 或 `cache` 的范围

javascript - 去抖动和返回

c++ - 类成员在实例初始化时需要这个指针