나는 내가 이해하지 못하는 작은 문제가있다.파이썬 - 왜 객체의 새로운 인스턴스를 만들지 않는가?
object.appendMethod()
을 그리고 실제로 내가 여기서 someObject의 같은 인스턴스 목록을 추가합니다
def appendMethod(self, newInstance = someObject()):
self.someList.append(newInstace)
내가 속성없이이 메소드를 호출
내가하는 방법이있다.
하지만 그것은로 변경하는 경우 :
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
를 볼 수 있지만 약 * * 기본값을 만들 때입니다. @tomek은 모든 함수가'__defaults__' 속성에 기본값의 **'튜플 (tuple) ** **을 유지한다는 것을 명심하십시오. 그러나 이것은 무엇을 의미합니까? 음, 분명히'tuple'은 불변의 함수이기 때문에 호출 될 때마다 디폴트 값을 만들 수 없기 때문에 디폴트 값은 함수 * 정의 *에서만 생성됩니다. 'someObject'를'def func() : print ("called")'와 같은 함수로 변경하고이 함수가 언제 호출되는지보십시오. – Bakuriu
이것은 좋은 질문입니다. 함수가 함수 정의가 아닌 함수 실행에서 평가되는 2 급 객체 인 곳에서 C++에서 왔을 때 확실히 혼란 스러웠습니다. – Shashank