在现代Python中扩展父类方法的正确方法是什么 [英] What is the correct way to extend a parent class method in modern Python

查看:180
本文介绍了在现代Python中扩展父类方法的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常这样做:

class Person(object):
    def greet(self):
        print "Hello"

class Waiter(Person):
    def greet(self):
        Person.greet(self)
        print "Would you like fries with that?"

Person.greet(self)行似乎不对。如果我改变了Waiter继承的类,我将不得不追踪其中的每一个并将它们全部替换掉​​。

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.

这样做的正确方法是什么是现代的Python吗? 2.x和3.x都有,我知道3中这个区域有变化。

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.

推荐答案

你使用 super


返回一个代理对象,该对象将
方法调用委托给父类或兄弟类
类。这对
访问在类中重写
的继承方法很有用。搜索
顺序与
getattr()使用的顺序相同,但跳过类型本身

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.

换句话说,对 super 的调用会返回一个假对象,该对象将属性查找委托给上面的类你在继承链。注意事项:

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:


  • 这不适用于旧式类 - 所以如果你使用的是Python 2.x,你需要确保层次结构中的顶级类继承自 object

  • 您需要将自己的类和实例传递给<$ c $ Python 2.x中的c> super 。此要求在3.x中被免除。

  • 这将正确处理所有多重继承。 (如果在Python中有多重继承树,则会生成方法解析顺序并查找通过这个顺序的父类。)

  • 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.)

注意:有很多地方对Python中的多重继承感到困惑。您可能需要阅读 super() Considered Harmful 。如果您确定要坚持使用单个继承树,并且不打算更改所述树中类的名称,则可以像上面那样对类名进行硬编码,一切都会正常工作。

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.

这篇关于在现代Python中扩展父类方法的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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