Python继承与多态

Python

1.多态与继承

Python多态

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值