如何在Python 3.6.1中继承类属性

时间:2017-06-05 21:22:46

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

我正在试图弄清楚如何将所有属性/方法从一个类继承到另一个类。我基于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 个答案:

答案 0 :(得分: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中的参数