如何继承父类的所有功能?

时间:2018-06-22 20:33:32

标签: python class object inheritance super

我正在尝试将ete3.Tree的所有功能继承到名为TreeAugmented的新类中,但是不是所有的方法和属性都可用吗?

我应该在__init__中使用super做些什么吗?似乎对于super,您必须像The inheritance of attributes using __init__中那样指定各个属性。

我可以在名为tree的类中拥有另一个对象,该对象存储ete3.Tree中的所有内容,但是我希望能够将这些对象与ete3包中的函数一起使用。 / p>

是否可以从父类继承所有内容?

import ete3
newick = "(((petal_width:0.098798,petal_length:0.098798):0.334371,"
         "sepal_length:0.433169):1.171322,sepal_width:1.604490);"

print(ete3.Tree(newick).children)
# [Tree node '' (0x1296bf40), Tree node 'sepal_width' (0x1296bf0f)]

class TreeAugmented(ete3.Tree):
    def __init__(self, name=None, new_attribute=None):
        self.name = name # This is an attribute in ete3 namespace
        self.new_attribute = new_attribute

x = TreeAugmented(newick)
x.children

追踪

AttributeError                            Traceback (most recent call last)
<ipython-input-76-de3016b5fd1b> in <module>()
      9
     10 x = TreeAugmented(newick)
---> 11 x.children

~/anaconda/envs/python3/lib/python3.6/site-packages/ete3/coretype/tree.py in _get_children(self)
    145
    146     def _get_children(self):
--> 147         return self._children
    148     def _set_children(self, value):
    149         if type(value) == list and \

AttributeError: 'TreeAugmented' object has no attribute '_children'

1 个答案:

答案 0 :(得分:2)

  

有没有办法从父类继承所有内容?

默认情况下就是这种情况。子类继承其未覆盖的内容。

您的孩子上课几乎是正确的。由于您覆盖了__init__方法,因此您要确保父类的__init__方法也被调用。

这是通过super实现的:

class TreeAugmented(ete3.Tree):
    def __init__(self, newick=None, name=None, format=0, dist=None, support=None, new_attribute=None):
        super().__init__(newick=newick, format=format, dist=dist, support=support, name=name)
        self.new_attribute = new_attribute

无需执行self.name = name,因为它是在super().__init__()中完成的。您需要注意的是孩子班级的具体情况。

使用* args / ** kwargs

此外,由于您无需触摸所有这些父init属性,因此可以使用args / kwargs使代码更清晰:

class TreeAugmented(ete3.Tree):
    def __init__(self, newick=None, new_attribute=None, *args, **kwargs):
        super().__init__(newick=newick, *args, **kwargs)
        self.new_attribute = new_attribute

在此示例中,我将newick保留为第一位置,并确定所有其他参数在new_attribute之后还是关键字参数。

设置父类参数

如果不想,您不必公开父类的所有参数。例如,如果您想创建一个只能做format 3 "all branches + all names"的子类,则可以通过编写以下内容来强制使用格式:

class TreeAugmented(ete3.Tree):
    def __init__(self, newick=None, name=None, dist=None, support=None, new_attribute=None):
        super().__init__(newick=newick, format=3, dist=dist, support=support, name=name)
        self.new_attribute = new_attribute

(这只是一个暴露常规做法的虚拟示例。在您的上下文中,这可能没有意义。)