【发布时间】: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