Python - 为什么它不创建对象的新实例?

Tom*_*zyk 6 python class object instance

我有一点我不明白的问题.

我有一个方法:

def appendMethod(self, newInstance = someObject()):
    self.someList.append(newInstace)
Run Code Online (Sandbox Code Playgroud)

我称之为没有属性的方法:

object.appendMethod()
Run Code Online (Sandbox Code Playgroud)

实际上,我使用someObject的相同实例附加列表.

但是,如果我将其更改为:

def appendMethod(self):
    newInstace = someObject()
    self.someList.append(newInstance)
Run Code Online (Sandbox Code Playgroud)

我每次都得到该对象的新实例,有什么区别?

这是一个例子:

class someClass():
    myVal = 0

class otherClass1():

    someList = []

    def appendList(self):
        new = someClass()
        self.someList.append(new)

class otherClass2():

    someList = []

    def appendList(self, new = someClass()):
        self.someList.append(new)

newObject = otherClass1()
newObject.appendList()
newObject.appendList()
print newObject.someList[0] is newObject.someList[1]
>>>False

anotherObject = otherClass2()
anotherObject.appendList()
anotherObject.appendList()
print anotherObject.someList[0] is anotherObject.someList[1]
>>>True
Run Code Online (Sandbox Code Playgroud)

Cam*_*arr 3

这是因为您将默认参数分配为可变对象。

\n\n

在Python中,函数是一个在定义时被评估的对象,因此当您键入时,def appendList(self, new = someClass())您被定义new为函数的成员对象,并且它不会在执行时重新评估。

\n\n

请参阅Python 中的 \xe2\x80\x9cLeast Astonishment\xe2\x80\x9d:可变默认参数

\n