我试图将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'
默认情况下是这样的。子类继承它不重写的内容。你知道吗
你的孩子课几乎是对的。因为重写了
__init__
方法,所以需要确保父类的__init__
方法也被调用。你知道吗这是通过
super
实现的:不需要做
self.name = name
,因为它是在super().__init__()
中完成的。你所要关心的就是你的孩子们的具体情况。你知道吗使用*args/**kwargs
另外,由于没有触及所有这些父init属性,因此可以使用args/kwargs使代码更清晰:
在本例中,我将
newick
保留为第一个位置,并确定所有其他参数都在new_attribute
之后,或者是关键字参数。你知道吗设置父类参数
如果不想,不必公开父类中的所有参数。例如,如果您想创建一个只执行format 3 "all branches + all names"操作的子类,您可以通过编写以下命令来强制格式化:
(这只是一个虚拟的例子来展示一种常见的做法。在你的上下文中可能没有意义。)
相关问题 更多 >
编程相关推荐