如何从 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章