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

后端 未结 15 2675
無奈伤痛
無奈伤痛 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 11:05

    There is a super() in python also.

    Example for how a super class method is called from a sub class method

    class Dog(object):
        name = ''
        moves = []
    
        def __init__(self, name):
            self.name = name
    
        def moves_setup(self,x):
            self.moves.append('walk')
            self.moves.append('run')
            self.moves.append(x)
        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().moves_setup("hello world")
            self.moves.append('fly')
    dog = Superdog('Freddy')
    print (dog.name)
    dog.moves_setup()
    print (dog.get_moves()) 
    

    This example is similar to the one explained above.However there is one difference that super doesn't have any arguments passed to it.This above code is executable in python 3.4 version.

提交回复
热议问题