问题描述
主类有一个__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 (将#修改为@)