前言
使用super函数可以在子类中直接调用父类的方法。通常情况下,我们会将一些通用的属性或方法定义在父类中,子类可以直接使用父类中定义的方法。我们通过super
函数便可将父类中定义的方法"拷贝"到子类中。
实践
我们定义Variable
用于存放子类用到的公共变量:
class Variable:
def __init__(self, long, wide):
self.long = long
self.wide = wide
可见我们指定了长、宽两个变量。接下来我们定义子类Square
,其继承于父类Variable
。并使用父类中定义的变量:
class Square(Variable):
def __init__(self, long, wide):
super().__init__(long, wide)
def area(self):
return self.long * self.wide
可见我们的子类Square
通过super()
函数将父类中的__init__
函数直接"拷贝"过来了,所以我们可以直接使用self.long
、self.wide
这两个变量,并通过方法area
求取面积:
square = Square(2, 3)
print(square.area())
>>> 6
我们有时候需要在父类的基础上添加新的内容,例如我们要求体积,那么还需要一个变量high
:
class Cube(Variable):
def __init__(self, long, wide, high):
super().__init__(long, wide)
self.high = high
def volume(self):
return self.long * self.wide * self.high
这里,我们首先通过super()
函数将父类中的两个变量引进,然后通过self.high = high
定义我们新的变量high
。然后通过函数volume
求体积:
cube = Cube(3, 3, 3)
print(cube.volume())
>>> 27
最后添加一个小例子,大家分析一下计算结果:
class Variable:
def __init__(self, long, wide):
self.long = long
self.wide = wide
class Square(Variable):
def __init__(self, long, wide):
super().__init__(long, wide)
def area(self):
return self.long * self.wide
class Cube(Square):
def __init__(self, long, wide, high):
super().__init__(long, wide)
self.high = high
def volume(self, number):
return super().area() * self.high * number
square = Square(2, 3)
cube = Cube(3, 3, 3)
print(square.area())
print(cube.volume(5))
>>> 6
>>> 135
以上便是super函数的全部内容,感谢大家的收藏、点赞、评论。我们下一节将介绍抽象类(Abstract Classes),敬请期待~