How to inherit all functionality of a parent class?
我正试图将
我应该在
我可以在类中有另一个名为
有没有一种方法可以从父类继承所有内容?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 |
追溯
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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?
默认情况下是这样的。子类继承它不重写的内容。
你的儿童班几乎是对的。因为您重写了
这是通过使用
1 2 3 4 | 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 |
无需执行
此外,由于您不接触所有这些父init属性,因此可以使用args/kwargs使代码更清晰:
1 2 3 4 | 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 |
在这个例子中,我将
如果不想公开父类的所有参数,则不必公开父类的所有参数。例如,如果要创建一个只执行格式3"所有分支+所有名称"的子类,可以通过编写以下内容强制执行格式:
1 2 3 4 | 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 |
(这只是一个虚伪的例子来揭示一种常见的做法。这在你的上下文中可能没有意义。)