Python - why doesn't it create a new instance of an object?

I have a little problem that I do not understand.

I have a method:

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

I call this method without attributes:

 object.appendMethod() 

And actually I am adding a list with the same instance of someObject.

But if I change it to:

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

I get a new instance of this object every time, what's the difference?

Here is an example:

 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 
+6
source share
1 answer

This is because you are assigning your default argument as a mutable object.

In python, a function is an object that is evaluated when it is defined. Therefore, when you enter def appendList(self, new = someClass()) , you define new as a member object of the function, and DO NOT reevaluate the execution time.

see "Least Surprise" in Python: argument argument resolved by argument

+2
source

Source: https://habr.com/ru/post/953262/


All Articles