如何解决使用动态生成的方法在Python中继承类
我创建了一个包含3个主要内容的模块:
- 具有
__new__
方法的主类和继承该方法的子类; - 可以将方法与现有类相关联的
make_method
装饰器; - 一个
generic
类。
主类有一个__new__
方法,该方法使用make_method
装饰器创建可用于任何子类的绘图函数。这是示例:
class MainClass():
FREEPARAMETERS = ['mu_1','sigma_1']
PLTALL = ["self.param['" + k + "']" for k in FREEPARAMETERS]
def __new__(cls,*arg,**kwargs):
'''Returns the class with dynamically generated methods'''
obj = super(MainClass,cls).__new__(cls)
exec("@make_method(MainClass)\n" +
"def plot_a(self,x_lin):\n" +
" return self.likelihood_tot(x_lin,%s)"
% (",".join(MainClass.PLTALL)))
return(obj)
然后,如果我这样创建ChildClass
:
class ChildClass(MainClass):
FREEPARAMETERS = ['mu_1','sigma_1','mu_2','sigma_2']
PLTALL = ["self.param['" + k + "']" for k in FREEPARAMETERS]
它将具有plot_a
方法,该方法仅需要具有x_lin
,而无需手动输入参数(提供了采用正确参数的likelihood_tot
方法)。 / p>
所有这些都能很好地工作(对于我实际需要的东西可能有点过大,但这很不错)。然后是generic
类:
class generic():
'''Usage:
gen = MyModule.generic()
gen.set_model('model')
fitted_model_1 = gen.fit(dataset1)
fitted_model_2 = gen.fit(dataset2)
fitted_model_1.plot_a(x_lin)
fitted_model_2.plot_a(x_lin)'''
def set_model(self,classname):
'''Associates an uninstantiated class to self.model from its string'''
self.model = getattr(sys.modules[__name__],classname)
def fit(self,dataset,**kwargs):
'''Instantiates the class with the pandas,apply the `minimize` method,and gives that back as an output'''
model = self.model(dataset)
model.minimize(**kwargs)
return(model)
如其文档中所述,其想法是能够调用一个通用模型,例如,我可以向该通用模型传递不同的数据集,而不必每次都手动实例化该类。效果很好。
执行以下操作时会出现问题,其中ChildClass1
和ChildClass2
具有不同的FREEPARAMETERS
:
gen.set_model('ChildClass1')
fitted_childclass1 = gen.fit(dataset)
gen.set_model('ChildClass2')
fitted_childclass2 = gen.fit(dataset)
fitted_childclass2.plot_a(x_lin)
fitted_childclass1.plot_a(x_lin)
与plot_a(x_lin)
类的最后一次调用关联的第一个generic
可以正常工作。然而,第二个函数根据最近实例类与之前实例之间的相对数量KeyError: 'mu_2'
给出了TypeError: likelihood_tot() missing n required positional arguments
或FREEPARAMETERS
,这意味着动态生成的plot_a
的{{1}}具有参数fitted_childclass1
。
但是,当致电fitted_childclass2
或childclass1.PLTALL
时,我确实得到了预期的结果。似乎在实例化之后它们并没有互换。所有不是动态生成的方法都是正确的。
我当然可以在每个函数之间调用childclass2.PLTALL
函数,但这显然不是重点。我希望plot_a
和childclass1
的行为就像我实例化它们一样:
childclass2
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。