首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >修复类的参数

修复类的参数
EN

Stack Overflow用户
提问于 2018-08-08 16:33:35
回答 3查看 49关注 0票数 0

我有一个接受三种不同objective类型的类。让我们假设类名是BaseEstimator,并且它接受三种模式-- 'obj_1''obj_2''obj_3'作为objective参数。现在我想创建三个类,每个对象类型一个。默认情况下,这些类将传入每种objective类型。例如,FixedEstimator_Obj1将包含objective = 'obj_1'

我知道我可以通过在FixedEstimator_Obj1类的__init__函数中这样做来做到这一点:

代码语言:javascript
复制
class FixedEstimator_Obj1:
    def __init__(self):
        self.base_estimator = BaseEstimator(objective='obj_1')

这种方法的问题是,当我想要使用BaseEstimator的属性或方法访问它时,我必须通过base_estimator访问它,如下所示

代码语言:javascript
复制
fe_obj1 = FixedEstimator_Obj1()
fe_obj1.base_estimator.some_method()

我正在寻找的是一种方法,可以让我把上面的代码写成

代码语言:javascript
复制
fe_obj1.some_method()

我该怎么做呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-08-08 16:54:25

如果你真的需要这三个不同的类,也许你可以使用传统的继承,覆盖一个参数:

代码语言:javascript
复制
class FixedEstimator_Obj1(BaseEstimator):
    def __init__(self, *args, **kwargs):
        kwargs['objective'] = 'obj_1'
        super(FixedEstimator_Obj1, self).__init__(*args, **kwargs)

在上面的示例中,这是调用BaseEstimator __init__objective固定为关键字参数,但您也可以修复位置参数:

代码语言:javascript
复制
class FixedEstimator_Obj1(BaseEstimator):
    def __init__(self, *args, **kwargs):
        super(FixedEstimator_Obj1, self).__init__('obj_1', *args, **kwargs)
票数 1
EN

Stack Overflow用户

发布于 2018-08-08 16:56:22

继承可能是这里的一种解决方案:

你要找的是super()

super允许您隐式引用对象的父类:

代码语言:javascript
复制
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()
票数 1
EN

Stack Overflow用户

发布于 2018-08-08 16:50:26

为什么需要为每个objective参数创建单独的类?

因为根据您陈述问题的方式,一个类应该足够了。

代码语言:javascript
复制
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.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51742139

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档