Python:如何从超类创建子类? [英] Python: How do I make a subclass from a superclass?

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

问题描述

在 Python 中,如何从超类创建子类?

In Python, how do you make a subclass from a superclass?

推荐答案

# Initialize using Parent
#
class MySubClass(MySuperClass):
    def __init__(self):
        MySuperClass.__init__(self)

或者,更好的是,使用 Python 的内置函数 super()(请参阅 Python 2/Python3 文档)可能是调用父级初始化的更好方法:

Or, even better, the use of Python's built-in function, super() (see the Python 2/Python 3 documentation for it) may be a slightly better method of calling the parent for initialization:

# Better initialize using Parent (less redundant).
#
class MySubClassBetter(MySuperClass):
    def __init__(self):
        super(MySubClassBetter, self).__init__()

或者,和上面一样,除了使用 super() 的零参数形式,它只在类定义中工作:

Or, same exact thing as just above, except using the zero argument form of super(), which only works inside a class definition:

class MySubClassBetter(MySuperClass):
    def __init__(self):
        super().__init__()

这篇关于Python:如何从超类创建子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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