2014-02-08 5 views
0

내 자신의 클래스를 만들 때 메서드 작동 방식을 이해하는 데 문제가 있습니다.클래스 메서드 이해 : 메서드 호출 오류

이 내 수업 방법 :

def compare_coll(self,coll_1, coll_2) -> None: 
    ''' compares two collections of key words which are dictionaries, 
    <coll_1> and <coll_2>, and removes from both collections every word 
    that appears in both collection''' 


    overlap = set(coll_1).intersection(set(coll_2)) 
    for key in overlap: 
     del coll_1[key], coll_2[key] 

, 키가 단어와 값입니다 사전을 저장하는 소위 '카운트'발생 그들의 수는 하나 개의 인스턴스 변수 내 클래스의 Collection_of_word_counts '입니다했다. 이니셜 라이저는 txt 파일의 단어를 읽고 self.counts에 저장합니다.

이 방법을 사용하는 방법을 모르겠습니다. 나는 그것을 올바르게 구현 한 것을 압니다.

>>> c1.compare_coll(c2) 

는 생산 :

>>> Collection_of_word_counts.compare_coll(c1,c2) 

Traceback (most recent call last): 
File "<string>", line 1, in <fragment> 
builtins.TypeError: compare_coll() missing 1 required positional argument: 'coll_2' 

와 동일한 오류가 발생.

셸에서 어떻게 사용하는지 정확히 모르겠습니다.

답변

1

compare_coll 메서드는 클래스 메서드가 아닌 인스턴스 메서드입니다. 일반적으로 self이라고하는 인스턴스 메서드의 첫 번째 인수는 메소드가 호출되는 클래스의 인스턴스입니다 (예 : c1.compare_coll(c2)의 경우 self == c1). 따라서 다른 인수 하나만 입력하면됩니다. 시도 :

def compare_coll(self, other) -> None: 
    overlap = set(self.counts).intersection(set(other.counts)) 
    for key in overlap: 
     del self.counts[key], other.counts[key] 

c1.compare_coll(c2) 또는 Collection_of_word_counts.compare_coll(c1, c2) 중 하나에 대해 작동합니다.

메서드 내에서 두 인스턴스 각각에 대해 counts을 직접 참조했습니다.

+0

감사합니다. 나는 지금 아주 명확하게 이해한다. –

+0

클래스 메서드와 인스턴스 메서드의 차이점에 대해 약간 혼란 스럽지만 좀 더 연구 할 것입니다. –

+0

이것과 [이전 질문] (http://stackoverflow.com/questions/21560404/understanding-list-comprehension) : http://stackoverflow.com/help/someone-answers – jonrsharpe

관련 문제