将实例化对象的方法 给新的对象用
class SharedKls:
def __setattr__(self, key, value):
if not hasattr(SharedKls, key):
if callable(value): # 是否可以调用
# 不加staticmethod,会默认传self
value = staticmethod(value)
setattr(SharedKls, key, value)
kls_a = SharedKls()
kls_b = SharedKls()
kls_a.attr_a = 1
def func(self, x):
return x * x
kls_a.method_a = lambda x: x * 3
assert kls_b.method_a(3) == 9