在__init __

时间:2019-05-13 22:10:14

标签: python inheritance

我正在创建一个将在启动时组装在一起的其他类的集合。

现在,我班上的init函数看起来像这样:

class RandomForest():
    def __init__(self, n_estimators=10, min_leaf=5, sample_size = 2/3, min_impurity=1e-5):
    self.n_estimators = n_estimators
    self.tree         = None
    self.min_leaf     = min_leaf
    self.sample_size  = sample_size
    self.min_impurity = min_impurity
    self.trees        = [self.tree(min_leaf=self.min_leaf, impurity_threshold=self.min_impurity) for i in range(n_estimators)]

这个想法是,RandomForest类将有两个子类,它们将对属性self.tree使用不同的类,这就是我想在初始化时修改的每个。

现在我有一个Random Forest的子类:

class RandomForestRegressor(RandomForest):
    def __init__(self):
        self.tree = DecisionTreeRegressor
        super().__init__() 

在我的脑海中,我将self.tree的值设置为要初始化的类,然后self.trees将是一个包含DecisionTreeRegressor()的10个单独实例的列表,但是我收到错误消息:

TypeError: 'NoneType' object is not callable

因此,显然self.tree的值没有被更新。

此外,我希望这是用户在启动课程时做出的选择,并且应该在没有选择的情况下自动进行设置。

Random Forest的继承类设置此属性的正确方法是什么?

**编辑:**这将在Python 3中完成。

2 个答案:

答案 0 :(得分:2)

您设置了值,但随后调用了super方法,该方法立即将其设置为None,因此会出现错误。

解决方案只是在调用super之后进行设置。

答案 1 :(得分:1)

如果在调用超类init之前设置属性树,则会在类实例中拥有它,但是在该超类init之后进行调用,您还可以这样做:

    self.tree         = None

将您先前设置的树替换为值None。

您可以:

  • 如果没有任何内容取决于self.tree值,请在设置树变量之前调用super().__init__()
class SupClass:
    def __init__():
        self.tree = None

class SubClass(SupClass):
    def __init__():
        super().__init__() # It would set self.tree = None
        self.tree = Something # It will set self.tree to Something

  • 有条件地将树设置为您的超类中的树,例如:self.tree = self.tree if hasattr(self, 'tree') else None,只有在之前未设置self.tree时,它才会设置None。
class SupClass:
    def __init__():
        self.tree = self.tree if hasattr(self, 'tree') else None  # Note, it check if value is defined before, in other case you may need to check if value is not None too.

class SubClass(SupClass):
    def __init__():
        self.tree = Something # It will set self.tree to Something
        super().__init__() # It will leave Something, because there is value

  • 将其作为SupClass初始化参数
class SupClass:
    def __init__(tree=None):
        self.tree = tree

class SubClass(SupClass):
    def __init__():
        super().__init__(tree=Something) # Note that your SupClass init method has no argument tree, you use it only in superclass init call.