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

How to inherit all functionality of a parent class?

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

__init__super 中有什么我应该做的吗?似乎 super 你必须像 The inheritance of attributes using __init__.

那样指定单独的属性

我可以在 class 中有另一个名为 tree 的对象,我在其中存储 ete3.Tree 中的所有内容,但我希望能够将这些对象与 ete3包。

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

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'

Is there a way to just inherit everything from the parent class?

默认情况下是这样的。 child class 继承了它没有覆盖的内容。

你child class几乎是正确的。由于您覆盖了 __init__ 方法,因此您要确保 parent class 的 __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__() 中完成。您只需要关心您的 child class.

的具体情况

使用 *args/**kwargs

此外,由于您没有触及所有这些 parent 初始化属性,您可以使用 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 之后或者是关键字参数。

设置 parent class 参数

如果您不想,则不必公开 parent class 中的所有参数。例如,如果你想创建一个只能做 format 3 "all branches + all names" 的 child class,你可以通过写来强制格式:

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

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