2014-12-11 1 views
1

__get__ 설명자가 아래 코드에서 무엇을하는지 이해하려고합니다. __get__에 대한 모든 자습서를 작성했지만 여전히 여기에서 무슨 일이 일어나는지 알 수 없습니다.설명자 __get__ 메서드

class A: 
    def __init__(self, socket, address=None): 
     self.sock = socket 
     self.address = address 
     self.verbose = True 

class B(): 
    def __init__(self): 
     self.clients = [] 
     self.slaves = [] 
     self.pending_tasks = [] 
     self.running_tasks = {} 
     self.finished_tasks = {} 


class C(B): 
    def __init__(self, *args, **kwargs): 
     super(C, self).__init__(*args, **kwargs) 


    def handle_new_connection(self, socket, address): 
     link = A(socket, address) 

    def bind(self, host, port): 
     handle = self.handle_new_connection.__get__(self, C) 

if __name__ == "__main__": 
    m = C() 
    m.bind('0.0.0.0', 6666) 

바인드 방법에서 __get__은 무엇을 수행합니까?

+0

'self.handle_new_connection'이 바인딩을 이미 * 이미 *하고 있기 때문에 * 전체 중복 *입니다. –

+0

변수가 gevent.server.StreamServer로 전송됩니다. 핸들에서 __get__이 (가) NetLink의 양말과 주소를 반환한다고 생각합니까? 내가 맞습니까? – user3648963

답변

2

__get__ 전화가 중복되어 쓸모가 없습니다. 이 방법은 이미 바인딩 모든 __get__ 호출하지 다시 결박입니다 : 이미 바인딩 방법 개체에 __get__ 메소드 호출은 바인딩 된 메서드 개체 자체를 반환하는 방법을

>>> m = C() 
>>> m 
<__main__.C object at 0x10b2cbeb8> 
>>> m.handle_new_connection 
<bound method C.handle_new_connection of <__main__.C object at 0x10b2cbeb8>> 
>>> m.handle_new_connection.__get__(m, C) 
<bound method C.handle_new_connection of <__main__.C object at 0x10b2cbeb8>> 

참고; 아무것도 여기에서 바뀌지 않았다.

이 후프를 뛰어 넘기 위해 생각할 수있는 유일한 이유는 (파이썬 메소드 룩업이 이미 함수 설명자를 호출했다는 것을 이해하는 것 외에는) 클래스 메소드로 메소드를 호출 할 수 있기 때문입니다. 인스턴스하지만 클래스) 아닌 명시 적으로 첫 번째 인수 :

>>> C.handle_new_connection 
<function C.handle_new_connection at 0x10b5e32f0> 
>>> C.handle_new_connection.__get__(C, C) 
<bound method type.handle_new_connection of <class '__main__.C'>> 
>>> C.bind(C, '0.0.0.0', 6666) 

이 경우 self.handle_new_connection 원래 언 바운드 기능으로 해결하기 때문이다.

+0

감사! 고마워요! – user3648963

+0

코드가 여전히 잘못 작성되었습니다. 'handle_new_connection'을'@classmethod' (또는'@ staticmethod')로 선언하는 것이 더 합리적입니다. – Kevin

+0

@ 케빈 : 절대적으로. 나는 "그들이 무엇을하고 있는지 이해하지 못한다"는 설명을 여기에 들고있다. –