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

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

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

相关标签:
11条回答
  • 2020-11-29 19:30

    A heroic little example:

    class SuperHero(object): #superclass, inherits from default object
        def getName(self):
            raise NotImplementedError #you want to override this on the child classes
    
    class SuperMan(SuperHero): #subclass, inherits from SuperHero
        def getName(self):
            return "Clark Kent"
    
    class SuperManII(SuperHero): #another subclass
        def getName(self):
           return "Clark Kent, Jr."
    
    if __name__ == "__main__":
        sm = SuperMan()
        print sm.getName()
        sm2 = SuperManII()
        print sm2.getName()
    
    0 讨论(0)
  • 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__()
    
    0 讨论(0)
  • 2020-11-29 19:35

    There is another way to make subclasses in python dynamically with a function type():

    SubClass = type('SubClass', (BaseClass,), {'set_x': set_x})  # Methods can be set, including __init__()
    

    You usually want to use this method when working with metaclasses. When you want to do some lower level automations, that alters way how python creates class. Most likely you will not ever need to do it in this way, but when you do, than you already will know what you are doing.

    0 讨论(0)
  • 2020-11-29 19:40
    class Class1(object):
        pass
    
    class Class2(Class1):
        pass
    

    Class2 is a sub-class of Class1

    0 讨论(0)
  • 2020-11-29 19:41

    You use:

    class DerivedClassName(BaseClassName):
    

    For details, see the Python docs, section 9.5.

    0 讨论(0)
提交回复
热议问题