How to call a Parent Class's method from Child Class in Python?

后端 未结 15 2674
無奈伤痛
無奈伤痛 2020-11-22 10:14

When creating a simple object hierarchy in Python, I\'d like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for

15条回答
  •  礼貌的吻别
    2020-11-22 10:50

    Here is an example of using super():

    #New-style classes inherit from object, or from another new-style class
    class Dog(object):
    
        name = ''
        moves = []
    
        def __init__(self, name):
            self.name = name
    
        def moves_setup(self):
            self.moves.append('walk')
            self.moves.append('run')
    
        def get_moves(self):
            return self.moves
    
    class Superdog(Dog):
    
        #Let's try to append new fly ability to our Superdog
        def moves_setup(self):
            #Set default moves by calling method of parent class
            super(Superdog, self).moves_setup()
            self.moves.append('fly')
    
    dog = Superdog('Freddy')
    print dog.name # Freddy
    dog.moves_setup()
    print dog.get_moves() # ['walk', 'run', 'fly']. 
    #As you can see our Superdog has all moves defined in the base Dog class
    

提交回复
热议问题