【发布时间】:2019-03-05 20:48:09
【问题描述】:
我正在为进化算法开发一个代理类。我需要向它添加一个方法,该方法是从从父级继承的字符串生成的。 这是一个最小的例子
class Agent:
def __init__(self, s='\tif x > y:\n\t\treturn 1'):
self.f_template = f'def f(self, x,y):\n{s}'
我希望方法self.f(self, x,y) 具有self.f_template 作为函数体。
我知道我可以稍后添加它:
A = Agent()
exec(A.f_template)
A.f = partial(f, A)
>>> A.f(3,2)
1
但是是否有可能在__init__() 期间而不是之后实现相同的目标?
只需执行以下操作即可提高 NameError: name 'f' is not defined
class Agent:
def __init__(self, s='\tif x > y:\n\t\treturn 1'):
self.f_template = f'def f(self, x,y):\n{s}'
exec(self.f_template)
self.f = partial(f, self)
【问题讨论】: