Python将函数动态绑定为对象的成员方法

import types

class B:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def foo(self):
        pass

def A(self):
    print(self.x)
    print("A function...")


if __name__ == '__main__':
    b = B(1, 2)
    # 将A函数绑定到b对象上
    b.c = types.MethodType(A, b)
    # 第二种方法
    # setattr(b, "c", A.__get__(b, b.__class__))
    A(b)

'''
运行结果:
1
A function...
'''
posted @ 2022-05-07 08:58  道友请留步W  阅读(52)  评论(0编辑  收藏  举报