Python: How do I make a subclass from a superclass?

后端 未结 11 1823
日久生厌
日久生厌 2020-11-29 19:01

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

11条回答
  •  天命终不由人
    2020-11-29 19:32

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

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

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

提交回复
热议问题