简体   繁体   English

方法的描述符__get__

[英]Descriptor __get__ from method

I'm trying to understand what the __get__ descriptor is doing in code below. 我试图理解下面的代码中__get__描述符正在做什么。 I have wrote all tutorial about __get__ , still can't get what's happening here. 我已经写了有关__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)

What the __get__ is doing in bind method? __get__在bind方法中正在做什么?

The __get__ call is redundant and useless. __get__调用是多余且无用的。 The method is already bound , all the __get__ call does is bind it again: 该方法已经绑定 ,所有__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>>

Note how the __get__ method call on the already bound method object returned the bound method object itself; 注意,已经绑定的方法对象上的__get__方法调用如何返回绑定的方法对象本身。 nothing changed here. 这里什么都没有改变。

The only reason I can think of to jump through this hoop (other than not understanding that a Python method lookup already invoked the function descriptor), is to be able to call the method as a class method (by passing in an explicit first argument that is not an instance but a class): 我能想到的唯一原因就是跳过该箍(除了不了解Python方法查找已经调用了函数描述符),是能够将该方法作为类方法调用(通过传入一个显式的第一个参数不是实例而是类):

>>> 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)

because in that case self.handle_new_connection resolves into the original unbound function. 因为在这种情况下, self.handle_new_connection解析为原始的未绑定函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM