如何在Python的子类中调用父类的方法? [英] How to call a Parent Class's method from Child Class in Python?

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

问题描述

在Python中创建简单的对象层次结构时,我希望能够从派生类中调用父类的方法。在Perl和Java中,为此有一个关键字( 超级 )。在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() 函数:

Yes, but only with new-style classes. Use the super() function:

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

对于python< 3,使用:

For python < 3, use:

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

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

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