使用动态生成的方法在Python中继承类

问题描述

我创建了一个包含3个主要内容的模块:

  1. 具有__new__方法的主类和继承该方法的子类;
  2. 可以将方法与现有类相关联的make_method装饰器;
  3. 一个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)

如其文档中所述,其想法是能够调用一个通用模型,例如,我可以向该通用模型传递不同的数据集,而不必每次都手动实例化该类。效果很好。

执行以下操作时会出现问题,其中ChildClass1ChildClass2具有不同的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 argumentsFREEParaMETERS,这意味着动态生成plot_a的{​​{1}}具有参数fitted_childclass1

但是,当致电fitted_childclass2childclass1.pltALL时,我确实得到了预期的结果。似乎在实例化之后它们并没有互换。所有不是动态生成方法都是正确的。

我当然可以在每个函数之间调用childclass2.pltALL函数,但这显然不是重点。我希望plot_achildclass1的行为就像我实例化它们一样:

childclass2

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...