且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:如何从超类创建子类?

更新时间:2023-12-02 21:48:04

# 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__()