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

2024-09-27 00:22:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我应该在__init__super一起做些什么吗?似乎在super中必须指定单个属性,如The inheritance of attributes using __init__。你知道吗

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

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

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'

Tags: nameinselftreenew属性initdef
1条回答
网友
1楼 · 发布于 2024-09-27 00:22:29

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

默认情况下是这样的。子类继承它不重写的内容。你知道吗

你的孩子课几乎是对的。因为重写了__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

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

相关问题 更多 >

    热门问题