Python
1.多态与继承
shapeClass.py下
Shape父类: 等待引入
class shape:
def __init__(self,name):
self.name = name
def displayArea(self):
pass #跳过
def displayPerimeter(self): #计算周长
pass
def shapeCount(self): #计算当前图形数量
pass
在classExtend.py引入父类:
from shapeClass import shape as shape
长方形使用父类及重写求面积、周长方法:
class Rectangle(shape): #长方形实现父类 class rectangle(shape): #括号+shape重写父类
rectangleCount = 0 #类变量声明
def __init__(self,name,width,height):
super().__init__(name)
self.width = width
self.height = height
Rectangle.rectangleCount = Rectangle.rectangleCount + 1
def displayArea(self):
print(self.name, '面积:',self.width * self.height)
def displayPerimeter(self):
print(self.name, '周长', 2 * (self.width + self.height))
def displayRectangleCount(self):
print(Rectangle.rectangleCount)
三角形与圆形 继承父类
#三角形
class triangle(shape): #class triangle(shape):继承父类
def __init__(self,name,bottom,height):
super().__init__(name)
self.bottom = bottom
self.height = height
def displayArea(self):
print(self.name, '面积', self.bottom * self.height)
def displayPerimeter(self):
print(self.name, '周长:', self.bottom * 3)
class circle(shape):
circle = 0
def __init__(self,name,radius):
super().__init__(name)
self.radius = radius
def displayArea(self):
print(self.name, '面积',pi * self.radius * self.radius)
def displayPerimeter(self):
print(self.name, '周长', 2*pi*self.radius)
多态实现:
创建三个子类对象
用子类传入到showAreaAndZc(shape) 函数 用父类接受
shape1 = Rectangle('长方形',5,6)
# rectangle1.displayRectangleCount()
# rectangle1.displayArea()
shape2 = triangle('三角形',5,6)
shape3 = circle("圆形",5)
def showAreaAndZc(shape):
shape.displayArea()
shape.displayPerimeter()
showAreaAndZc(shape1)
showAreaAndZc(shape2)
showAreaAndZc(shape3)