ete3.Tree
呼び出されTreeAugmented
た新しいクラスにすべての機能を継承しようとしていますが、すべてのメソッドと属性が使用できるわけではありませんか?
私はで行うことになっていますものがある__init__
とはsuper
?__init__を使用した属性の継承のsuper
ように、個々の属性を指定する必要があるようです。
クラス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
ます。
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__()
。あなたが気にかけなければならないのはあなたの子供のクラスに特有のものだけです。
また、これらすべての親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
がキーワード引数の後に来るか、キーワード引数であると判断しました。
必要がない場合は、親クラスのすべてのパラメーターを公開する必要はありません。たとえば、フォーマット3「すべてのブランチ+すべての名前」のみを実行する子クラスを作成する場合は、次のように記述してフォーマットを強制できます。
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
(これは、一般的な方法を公開するための単なるダミーの例です。おそらく、コンテキストでは意味がありません。)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加