【问题标题】:How to inherit class attributes in Python 3.6.1如何在 Python 3.6.1 中继承类属性
【发布时间】:2017-06-05 21:22:45
【问题描述】:

我试图弄清楚如何将所有属性/方法从一个类继承到另一个类。我基于How to inherit a python base class?,但我不知道如何让它在我的简单示例中工作。在这个例子中,我只想创建一个新类,它具有RandomForestClassifier 的所有功能,但具有一个新属性(称为new_attribute)。在这种方法中,我不能使用原始RandomForestClassifier 的参数,但我可以添加我的新属性。

如何设置它,以便我可以使用原始 RandomForestClassifier 中的所有参数以及添加此 new_attribute

from sklearn.ensemble import RandomForestClassifier

class NewClassifier(RandomForestClassifier):
    def __init__(self, new_attribute):
        Super(RandomForestClassifier, self).__init__()
        self.new_attribute = new_attribute
A = NewClassifier(n_estimators=1, new_attribute=0)

错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-221-686839873f88> in <module>()
      5         Super(RandomForestClassifier, self).__init__()
      6         self.new_attribute = new_attribute
----> 7 A = NewClassifier(n_estimators=1, new_attribute=0)

TypeError: __init__() got an unexpected keyword argument 'n_estimators'

事后诸葛亮: 这是一个结构不佳的问题。我得到了上面的代码来处理下面的代码。但是,@Mseifert 在答案中有更好的表示:

class NewClassifier(RandomForestClassifier):
    def __init__(self, new_attribute, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_split=1e-07, bootstrap=True, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False, class_weight=None):
        RandomForestClassifier.__init__(self, n_estimators, criterion, max_depth, min_samples_split, min_samples_leaf, min_weight_fraction_leaf, max_features, max_leaf_nodes, min_impurity_split, bootstrap, oob_score, n_jobs, random_state, verbose, warm_start, class_weight)
        self.new_attribute = new_attribute
A = NewClassifier(n_estimators=1, new_attribute=0)

【问题讨论】:

  • 1.这些不是类属性,它们是初始化参数。 2. 您的子类__init__ 需要接受基类的所有参数并通过super 调用传递它们。 3. 你可以在 Python 3.x 中调用super().

标签: python python-3.x class object inheritance


【解决方案1】:

最简单的方法是接受new_attribute 作为第一个和必须的参数:

from sklearn.ensemble import RandomForestClassifier

class NewClassifier(RandomForestClassifier):
    def __init__(self, *args, **kwargs):  # just accept any argument
        # Find out what the value of "new_argument is" and remove it either from
        # the positional arguments (args) or keyword arguments (kwargs) so that
        # the remaining arguments can simply be passed to the super-class.
        if args:  # if there are positional arguments
            new_attribute = args[0]
            args = args[1:]
        else:     # no positional arguments
            new_attribute = kwargs.pop('new_attribute')

        super().__init__(*args, **kwargs)
        self.new_attribute = new_attribute

请注意,它是 super 而不是 Super,并且您不需要 python-3.x 中的参数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 2020-11-08
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 2016-07-08
    相关资源
    最近更新 更多