超级__str__心不是获取调用

问题描述:

我继承from sklearn.ensemble import RandomForestClassifier,和我想打印我的新的估计:超级__str__心不是获取调用

class my_rf(RandomForestClassifier): 
    def __str__(self): 
     return "foo_" + RandomForestClassifier.__str__(self) 

foo_my_rf()

我也试过:

class my_rf(RandomForestClassifier): 
    def __str__(self): 
     return "foo_" + super(RandomForestClassifier, self).__str__() 

与相同的结果。预期的东西非常喜欢sklearn默认行为:

 
>>> a = RandomForestClassifier() 
>>> print a 
RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', 
     max_depth=None, max_features='auto', max_leaf_nodes=None, 
     min_samples_leaf=1, min_samples_split=2, 
     min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1, 
     oob_score=False, random_state=None, verbose=0, 
     warm_start=False) 
>>> 

这也是结果,当我使用print a.__str__()

我错过了什么? 谢谢。

相关How do I change the string representation of a Python class?

+2

很明显,父类__str__实现是类的名称。你正确地调用它。 – jonrsharpe

+0

@jonrsharpe - 哎呀,编辑这个问题,以表明我在找什么。 – ihadanny

+0

您是否尝试过查看'__repr__'? – jonrsharpe

RandomForestClassifier__repr____str__查找类,他们是从(self)调用的类实例的名称。您应该直接引用超类的名称。

更新这就是你如何得到你想要的输出,虽然我没有得到,你为什么要这样的东西。 RandomForestClassifier__str____repr__有一个原因返回一个类的实际名称。这样你可以eval来恢复对象。无论如何,

In [1]: from sklearn.ensemble import RandomForestClassifier 
In [2]: class my_rf(RandomForestClassifier): 
    def __str__(self): 
     superclass_name = RandomForestClassifier.__name__ 
     return "foo_" + superclass_name + "(" + RandomForestClassifier.__str__(self).split("(", 1)[1] 

In [3]: forest = my_rf() 
In [4]: print forest 
foo_RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, 
    max_features='auto', max_leaf_nodes=None, min_samples_leaf=1, 
    min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10, 
    n_jobs=1, oob_score=False, random_state=None, verbose=0, 
    warm_start=False) 

更新2当你重写__init__,因为在超__str____repr__实现扫描传递给__init__参数列表中你没有参数。您可以通过运行以下代码清楚地看到它:

In [5]: class my_rf(RandomForestClassifier): 
    def __init__(self, *args, **kwargs): 
     RandomForestClassifier.__init__(self, *args, **kwargs) 
    def __str__(self): 
     superclass_name = RandomForestClassifier.__name__ 
     return "foo_" + superclass_name + "(" + RandomForestClassifier.__str__(self).split("(", 1)[1] 
In [6]: forest = my_rf() 
In [7]: print forest 
... 
RuntimeError: scikit-learn estimators should always specify their parameters in the signature of their __init__ (no varargs). <class '__main__.my_rf'> with constructor (<self>, *args, **kwargs) doesn't follow this convention. 
+0

虽然这不是OP所要求的,但它可能是他们真正想要的。 – 5gon12eder

+0

哎呀,编辑了这个问题,以表明我在找什么。 – ihadanny

+0

@ihadanny我更新了帖子 –