python super理解(二)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/luoganttcc/article/details/82959158

super() 的入门使用
在类的继承中,如果重定义某个方法,该方法会覆盖父类的同名方法,但有时,我们希望能同时实现父类的功能,这时,我们就需要调用父类的方法了,可通过使用 super 来实现,比如:

class Animal(object):
    def __init__(self, name):
        self.name = name
    def greet(self):
        print ('Hello, I am %s.' % self.name)
 
class Dog(Animal):
    def greet(self):
        super(Dog, self).greet()   # Python3 可使用 super().greet()
        print ('WangWang...')
        
dog = Dog('dog')
dog.greet()
Hello, I am dog.
WangWang...

原文

猜你喜欢

转载自blog.csdn.net/luoganttcc/article/details/82959158