从Python中的子类调用父类的方法? [英] Call a parent class's method from child class in Python?

查看:570
本文介绍了从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);
}



在pthon中,似乎我必须明确地儿童。
在上面的例子中,我必须做一些像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() function:

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

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

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

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