如何從 Python 中的子類調用父類的方法? - How do I call a parent class's method from a child class in Python?

問題:

When creating a simple object hierarchy in Python, I'd like to be able to invoke methods of the parent class from a derived class.在 Python 中創建簡單的對象層次結構時,我希望能夠從派生類調用父類的方法。 In Perl and Java, there is a keyword for this ( super ).在 Perl 和 Java 中,this 有一個關鍵字 ( super )。 In Perl, I might do this:在 Perl 中,我可能會這樣做:

package Foo;

sub frotz {
    return "Bamf";
}

package Bar;
@ISA = qw(Foo);

sub frotz {
   my $str = SUPER::frotz();
   return uc($str);
}

In Python, it appears that I have to name the parent class explicitly from the child.在 Python 中,我似乎必須從子類中明確命名父類。 In the example above, I'd have to do something like Foo::frotz() .在上面的示例中,我必須執行Foo::frotz()

This doesn't seem right since this behavior makes it hard to make deep hierarchies.這似乎不正確,因爲這種行爲使得很難建立深層次的層次結構。 If children need to know what class defined an inherited method, then all sorts of information pain is created.如果孩子們需要知道哪個類定義了一個繼承的方法,那麼各種信息痛苦就會產生。

Is this an actual limitation in python, a gap in my understanding or both?這是python的實際限制,我的理解上的差距還是兩者兼而有之?


解決方案:

參考一: https://en.stackoom.com/question/3NQw
參考二: https://stackoom.com/question/3NQw
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章