内置函数super多用于面向对象编程super函数返回一个代理对象,将方法调用委托给当前类的父类,可用于调用父类已经实现的方法。
super() -> same as super(__class__, <first argument>)
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
super函数有4种用法,我目前只参悟出了第3种用法,平时也只用到super(type, obj) 这种语法。
class Animal():
def __init__(self, name):
self.name = name
def drink(self):
print(f'{self.name} is drinking')
class Cat(Animal):
def __init__(self, name, age):
super(Cat, self).__init__(name)
self.age = age
def drink(self):
super(Cat, self).drink()
print("猫喝水时很安静")
cat = Cat("小花", 3)
cat.drink()
QQ交流群: 211426309