python 扩展方法_在现代Python中扩展父类方法的正确方法是什么

I frequently do this sort of thing:

class Person(object):

def greet(self):

print "Hello"

class Waiter(Person):

def greet(self):

Person.greet(self)

print "Would you like fries with that?"

The line Person.greet(self) doesn't seem right. If I ever change what class Waiter inherits from I'm going to have to track down every one of these and replace them all.

What is the correct way to do this is modern Python? Both 2.x and 3.x, I understand there were changes in this area in 3.

If it matters any I generally stick to single inheritance, but if extra stuff is required to accommodate multiple inheritance correctly it would be good to know about that.

解决方案

You use super:

Return a proxy object that delegates

method calls to a parent or sibling

class of type. This is useful for

accessing inherited methods that have

been overridden in a class. The search

order is same as that used by

getattr() except that the type itself

is skipped.

In other words, a call to super returns a fake object which delegates attribute lookups to classes above you in the inheritance chain. Points to note:

This does not work with old-style classes -- so if you are using Python 2.x, you need to ensure that the top class in your hierarchy inherits from object.

You need to pass your own class and instance to super in Python 2.x. This requirement was waived in 3.x.

This will handle all multiple inheritance correctly. (When you have a multiple inheritance tree in Python, a method resolution order is generated and the lookups go through parent classes in this order.)

Take care: there are many places to get confused about multiple inheritance in Python. You might want to read super() Considered Harmful. If you are sure that you are going to stick to a single inheritance tree, and that you are not going to change the names of classes in said tree, you can hardcode the class names as you do above and everything will work fine.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值