令人费解的范围行为

ele*_*ias 3 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
Run Code Online (Sandbox Code Playgroud)

输出是:

new instance
new instance
I get the ['wrong', 'behaviour']
Run Code Online (Sandbox Code Playgroud)

我本来期望的是,在列表INST1一无所知列表INST2,但不知何故,它看起来像的范围myList中 trascends类的实例.我发现这非常令人不安和令人费解,或者我在这里遗漏了什么?

谢谢!

Rik*_*ggi 6

您定义的方式myList是类属性.

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

class testclass:
    def __init__(self): 
        print "new instance"
        self.myList = []
Run Code Online (Sandbox Code Playgroud)

我们来试试吧:

>>> t1 = testclass()
new instance
>>> t2 = testclass()
new instance
>>> t1.myList.append(1)
>>> t2.myList.append(2)
>>> t1.myList
[1]
>>> t2.myList
[2]
Run Code Online (Sandbox Code Playgroud)

如果您对类属性感兴趣,请查看类文档.由于Python中的类也是对象,就像(几乎)Python中的所有内容一样,它们可以拥有自己的属性.