我很好奇如何在运行时为类创建自定义方法...
我的意思是例如方法名称、参数名称、从数据库读取的方法主体并将此方法分配给一个类或一个实例。
我发现可以添加已经编写的方法:
class A:
def __init__(self):
pass
def method(self):
return True
A.method = method
a = A()
print(a.method())
但我有兴趣从头开始完全组装一种新方法:
name = "method"
params = ["self"] # Params in list should be a strings
body = "return True"
# To create method from pieces
可以使用__dict__
吗?或者如何做到这一点?
方法是作为类的对象的另一个属性。它们可以像其他属性一样添加:
代码:
class A:
def __init__(self):
pass
def method(self):
return True
def another_method(self):
return False
setattr(A, 'another_method', another_method)
测试代码:
a = A()
print(a.another_method())
结果:
False
来自字符串的方法:
添加是否确实需要从数据库中获取方法,或者可以使用 exec ,例如:
method_string = """
def yet_another_method(self):
return type(self).__name__
"""
exec(method_string)
setattr(A, 'yet_another_method', yet_another_method)
a = A()
print(a.yet_another_method())
结果:
A
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句