BrightXiong 发表于 2023-2-13 22:12:06

多态

# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time   : 2023/2/13 21:39
# @Author : xiongming
# @File   : duotai.py
# @Desc   : 类继承中的多态

class Shape():
    def __init__(self, name):
      self.name = name
    def area(self):
            pass

class Square(Shape):
    def __init__(self, length):
      super().__init__("正方形")
      self.length = length
    def area(self):
      return self.length * self.length

class Circle(Shape):
    def __init__(self, radius):
      super().__init__("圆形")
      self.radius = radius
    def area(self):
      return 3.14 * self.radius * self.radius

class Triangle(Shape):
    def __init__(self, base, height):
      super().__init__("三角形")
      self.base = base
      self.height = height

    def area(self):
      return self.base * self.height / 2

s = Square(5)
c = Circle(6)
t = Triangle(3, 4)

print(s.name)
print(s.area())
print(c.area())
print(t.area())

class Cat:
    def __init__(self, name, age):
      self.name = name
      self.age = age
    def intro(self):
      print(f"我是一只猫,我叫{self.name},今年{self.age}岁了。")
    def say(self):
      print("mua~")

class Dog:
    def __init__(self, name, age):
      self.name = name
      self.age = age
    def intro(self):
      print(f"我是一只小狗,我叫{self.name},今年{self.age}岁了。")
    def say(self):
      print("wangwang~~")

class Pig:
    def __init__(self, name, age):
      self.name = name
      self.age = age
    def intro(self):
      print(f"我是一只小猪,我叫{self.name},今年{self.age}岁了。")
    def say(self):
      print("oink~~")

c = Cat("web", 4)
d = Dog("小黑", 3)
p = Pig("佩奇", 2)

#多态性表现
def animal(x):
    x.intro()
    x.say()

animal(c)
animal(d)
animal(p)
页: [1]
查看完整版本: 多态