本文介绍了Python中的动态/运行时方法创建(代码生成)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在运行时为方法生成代码.能够运行任意代码并具有文档字符串非常重要.
I need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring.
我想出了一个结合了exec
和setattr
的解决方案,这是一个虚拟的示例:
I came up with a solution combining exec
and setattr
, here's a dummy example:
class Viking(object):
def __init__(self):
code = '''
def dynamo(self, arg):
""" dynamo's a dynamic method!
"""
self.weight += 1
return arg * self.weight
'''
self.weight = 50
d = {}
exec code.strip() in d
setattr(self.__class__, 'dynamo', d['dynamo'])
if __name__ == "__main__":
v = Viking()
print v.dynamo(10)
print v.dynamo(10)
print v.dynamo.__doc__
是否有更好/更安全/更惯用的方式获得相同的结果?
Is there a better / safer / more idiomatic way of achieving the same result?
推荐答案
基于Theran的代码,但将其扩展到类的方法上:
Based on Theran's code, but extending it to methods on classes:
class Dynamo(object):
pass
def add_dynamo(cls,i):
def innerdynamo(self):
print "in dynamo %d" % i
innerdynamo.__doc__ = "docstring for dynamo%d" % i
innerdynamo.__name__ = "dynamo%d" % i
setattr(cls,innerdynamo.__name__,innerdynamo)
for i in range(2):
add_dynamo(Dynamo, i)
d=Dynamo()
d.dynamo0()
d.dynamo1()
应打印:
in dynamo 0
in dynamo 1
这篇关于Python中的动态/运行时方法创建(代码生成)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!