多态:
(一)代码如下:
class Cat:
def shout(self):
print("喵喵喵~")
class Dog:
def shout(self):
print("汪汪汪!")
def test(obj):
obj.shout()
cat = Cat()
cat.shout()
dog = Dog()
dog.shout()
test(cat)
test(dog)
(二)运行结果如下:
图形面积计算:
第一种:
(一)代码如下:
# 定义抽象形状父类Shape(包含未实现的get_area方法)
class Shape:
def get_area(self):
# 抽象方法,子类必须重写,否则调用时抛出异常
raise NotImplementedError("子类必须实现get_area方法")
# 圆形子类(继承Shape)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius # 半径
def get_area(self):
import math
return math.pi * self.radius ** 2 # 圆面积公式:πr²
# 矩形子类(继承Shape)
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length # 长
self.width = width # 宽
def get_area(self):
return self.length * self.width # 矩形面积公式:长×宽
# 三角形子类(继承Shape)
class Triangle(Shape):
def __init__(self, base, height):
self.base = base # 底
self.height = height # 高
def get_area(self):
return 0.5 * self.base * self.height # 三角形面积公式:1/2×底×高
# 计算任意形状面积的函数
def total_area(shape):
if isinstance(shape, Shape):
return shape.get_area()
else:
raise TypeError("参数必须是Shape类或其子类的实例")
# 示例使用
if __name__ == "__main__":
circle = Circle(5)
rectangle = Rectangle(4, 6)
triangle = Triangle(3, 8)
print(f"圆面积:{total_area(circle):.2f}") # 输出:圆面积:78.54
print(f"矩形面积:{total_area(rectangle)}") # 输出:矩形面积:24
print(f"三角形面积:{total_area(triangle)}") # 输出:三角形面积:12
(二)运行结果如下:
第二种:
(一)代码如下:
class Shape:
def get_area(self):
pass
class Circle(Shape):
def __init__(self, r):
self.r = r
def get_area(self):
return 3.14 * (self.r ** 2)
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def get_area(self):
return self.width * self.height
def total_area(shape):
print(f"面积为{shape.get_area()}")
c = Circle(2)
r = Rectangle(width=10, height=2)
total_area(c)
total_area(r)
(二)运行结果如下: