python子类如何调用父类属性,如何在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. 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);

}

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.

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

解决方案

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

class Foo(Bar):

def baz(self, arg):

return super().baz(arg)

For python < 3, use:

class Foo(Bar):

def baz(self, arg):

return super(Foo, self).baz(arg)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值