美文网首页
Python Bound Method and types.Me

Python Bound Method and types.Me

作者: aihex | 来源:发表于2016-12-14 08:31 被阅读0次

    when calling a bound method bm of o associated with f, it turns out to call bm.im_func(bm.im_self) where bm.im_func is f and bm.im_self is o.

    import types
    
    class A(object):
        def __call__(x, y, z):
            print('__call__ in A')
            print(x, y, z)
    
    class B(object):
        pass
    
    a, b = A(), B()
    
    # given two instance a and b where a must have a __call__ bound method
    # MethodType creates a bound method c with b as im_self,
    # c's underlying function im_func is the __call__ bound method of instane a
    c = types.MethodType(a, b)
    
    assert a is c.im_func.__call__.im_self
    assert b is c.im_self
    
    assert c.im_func.__call__.im_func is A.__call__.im_func
    
    c(1) # bound method call
    c.im_func(c.im_self, 1) # bound method call expansion, c.im_func is an instance with __call__ bound method
    c.im_func.__call__(c.im_self, 1) # the __call__ bound method expansion
    c.im_func.__call__.im_func(c.im_func.__call__.im_self, c.im_self, 1)
    
    

    相关文章

      网友评论

          本文标题:Python Bound Method and types.Me

          本文链接:https://www.haomeiwen.com/subject/anqimttx.html