我有一个接受三种不同objective类型的类。让我们假设类名是BaseEstimator,并且它接受三种模式-- 'obj_1'、'obj_2'和'obj_3'作为objective参数。现在我想创建三个类,每个对象类型一个。默认情况下,这些类将传入每种objective类型。例如,FixedEstimator_Obj1将包含objective = 'obj_1'。
我知道我可以通过在FixedEstimator_Obj1类的__init__函数中这样做来做到这一点:
class FixedEstimator_Obj1:
def __init__(self):
self.base_estimator = BaseEstimator(objective='obj_1')这种方法的问题是,当我想要使用BaseEstimator的属性或方法访问它时,我必须通过base_estimator访问它,如下所示
fe_obj1 = FixedEstimator_Obj1()
fe_obj1.base_estimator.some_method()我正在寻找的是一种方法,可以让我把上面的代码写成
fe_obj1.some_method()我该怎么做呢?
发布于 2018-08-08 16:54:25
如果你真的需要这三个不同的类,也许你可以使用传统的继承,覆盖一个参数:
class FixedEstimator_Obj1(BaseEstimator):
def __init__(self, *args, **kwargs):
kwargs['objective'] = 'obj_1'
super(FixedEstimator_Obj1, self).__init__(*args, **kwargs)在上面的示例中,这是调用BaseEstimator __init__将objective固定为关键字参数,但您也可以修复位置参数:
class FixedEstimator_Obj1(BaseEstimator):
def __init__(self, *args, **kwargs):
super(FixedEstimator_Obj1, self).__init__('obj_1', *args, **kwargs)发布于 2018-08-08 16:56:22
继承可能是这里的一种解决方案:
你要找的是super()
super允许您隐式引用对象的父类:
class BaseEstimator():
def __init__(self, objective):
self.objective = objective
def some_method(self):
return 'test_' + self.objective
class FixedEstimator_Obj1(BaseEstimator):
def __init__(self, objective):
super().__init__(objective=objective)
class FixedEstimator_Obj2(BaseEstimator):
def __init__(self, objective):
super().__init__(objective=objective)
FixedEstimator_Obj1('obj_1').some_method()
FixedEstimator_Obj2('obj_2').some_method()发布于 2018-08-08 16:50:26
为什么需要为每个objective参数创建单独的类?
因为根据您陈述问题的方式,一个类应该足够了。
class BaseEstimator:
def __init__(self, objective):
self.objective = objective
def some_method(self):
print f'My objective is {self.objective}'
fe_obj1 = BaseEstimator('to love')fe_obj1.some_method()输出My objective is to love.
https://stackoverflow.com/questions/51742139
复制相似问题