如何从 Python 中的子类调用父类的方法? [英] How do I call a parent class's method from a child class in Python?

查看:83
本文介绍了如何从 Python 中的子类调用父类的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中创建简单的对象层次结构时,我希望能够从派生类调用父类的方法.在 Perl 和 Java 中,对此有一个关键字 (super).在 Perl 中,我可能会这样做:

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. In Perl and Java, there is a keyword for this (super). In Perl, I might do this:

package Foo;

sub frotz {
    return "Bamf";
}

package Bar;
@ISA = qw(Foo);

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

在 Python 中,我似乎必须从子类中明确命名父类.在上面的示例中,我必须执行诸如 Foo::frotz() 之类的操作.

In Python, it appears that I have to name the parent class explicitly from the child. In the example above, I'd have to do something like 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.

这是python的实际限制,还是我的理解上的差距或两者兼而有之?

Is this an actual limitation in python, a gap in my understanding or both?

推荐答案

使用super() 函数:

class Foo(Bar):
    def baz(self, arg):
        return super().baz(arg)

对于 Python <3、您必须明确选择使用新样式类并使用:

For Python < 3, you must explicitly opt in to using new-style classes and use:

class Foo(Bar):
    def baz(self, arg):
        return super(Foo, self).baz(arg)

这篇关于如何从 Python 中的子类调用父类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆