2013-09-05 2 views
6

나는 내가 이해하지 못하는 작은 문제가있다.파이썬 - 왜 객체의 새로운 인스턴스를 만들지 않는가?

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 
+0

를 볼 수 있지만 약 * * 기본값을 만들 때입니다. @tomek은 모든 함수가'__defaults__' 속성에 기본값의 **'튜플 (tuple) ** **을 유지한다는 것을 명심하십시오. 그러나 이것은 무엇을 의미합니까? 음, 분명히'tuple'은 불변의 함수이기 때문에 호출 될 때마다 디폴트 값을 만들 수 없기 때문에 디폴트 값은 함수 * 정의 *에서만 생성됩니다. 'someObject'를'def func() : print ("called")'와 같은 함수로 변경하고이 함수가 언제 호출되는지보십시오. – Bakuriu

+0

이것은 좋은 질문입니다. 함수가 함수 정의가 아닌 함수 실행에서 평가되는 2 급 객체 인 곳에서 C++에서 왔을 때 확실히 혼란 스러웠습니다. – Shashank

답변

2

당신이 변경 가능한 객체로 기본 인수를 할당되어 있기 때문입니다 :

다음은 예입니다.

파이썬에서 함수는 정의 될 때 평가되는 객체이므로 def appendList(self, new = someClass())을 입력하면 new을 함수의 멤버 객체로 정의하며 실행시 다시 계산되지 않습니다.

이 질문에 * 엄격하게 * 변경이 용이 한 기본값으로 관련이없는 “Least Astonishment” in Python: The Mutable Default Argument

+0

감사합니다. 이제 어떻게됩니까? 그것은 나에게 직관적 인 카운터이지만, 나는 그것을 얻는다. 나는 함수를 객체로 생각하는 것을 잊었다. –

관련 문제