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

2024-06-02 08:37:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个小问题,我不明白。在

我有一个方法:

def appendMethod(self, newInstance = someObject()):
    self.someList.append(newInstace)

我将此方法称为不带属性的方法:

^{pr2}$

实际上,我用someObject的同一个实例附加了这个列表。在

但如果我把它改成:

def appendMethod(self):
    newInstace = someObject()
    self.someList.append(newInstance)

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

下面是一个例子:

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

Tags: 方法selfnewdefclassappendsomeclassnewinstance
1条回答
网友
1楼 · 发布于 2024-06-02 08:37:25

这是因为您将默认参数指定为可变对象。在

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

“Least Astonishment” in Python: The Mutable Default Argument

相关问题 更多 >