Python Bound Method and types.MethodType

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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • (这一篇,是我家闺女——伊州郡主的文章。这是郡主刚去德国不久,初二寒假我们一起去波恩游玩回来之后写的。彼时,在国内...
    书香云舍阅读 2,613评论 3 14
  • 这是天气晴朗的一天,湛蓝湛蓝的天上飘浮着朵朵白云,金黄色的阳光照耀着大地,我怀着激动的心情来到了清音公园,想看看清...
    浅雨悠扬阅读 1,501评论 0 1