super()函数的作用
1.super()调用父类方法,并重写>>>>>>减少代码量(Square类实现)
2.它允许您在子类中调用超类的方法。 这种情况的主要用例是扩展继承方法的功能。 (cube类实现)
3.控制MRO(方法解析顺序)的构建方式
class Rectangle(object):
def __init__(self,length,width):
self.length=length
self.width=width
def area(self):
return self.length*self.width
def Perimeter(self):
return 2*self.length+2*self.width
# class Square(object):
# def __init__(self,length):
# self.length=length
# def area(self):
# return self.length*self.length
# def Perimeter(self):
# return 4*self.length
class Square(Rectangle):
def __init__(self,length):
super().__init__(length,length)
class Cube(Square):
#表面积
def surface_area(self):
face_area=super().area()
return face_area*6
def volume(self):
face_area=super().area()
return self.length*face_area
def main():
rectangle=Rectangle(2,4)
print(rectangle.area(),rectangle.Perimeter())
square=Square(4)
print(square.area(),square.Perimeter())
cube=Cube(4)
print(cube.area(),cube.Perimeter(),cube.surface_area(),cube.volume())
if __name__ == '__main__':
main()