|
发表于 2023-1-2 21:08:01
|
显示全部楼层
本帖最后由 Ensoleile 于 2023-1-10 00:37 编辑
多态和鸭子类型
- #多态 -> 见机行事的行为
- print(3 + 5)
- print('learning' + 'python')
- #同样是‘+’,效果不同
- #有关类继承的方法,其实重写就是实现类继承的多态
- 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 ** 2
- 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(5)
- t = Triangle(3, 4)
- print(s.name, c.name, t.name, sep='\n')
- print(s.area(), c.area(), t.area(), sep='\n')
- 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('mau~')
- 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('wang~')
- 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('布布', 7)
- p = Pig('大肠', 5)
- def animal(x):
- x.intro()
- x.say()
- animal(c)
- animal(d)
- animal(p)
- #animal函数具有多态性,该函数接收不同的对象作为参数,并且不检查类型的情况下执行它的方法
- #鸭子类型:在编程中,我们并不会关心对象是什么类型,我们关心的是它的行为是否符合要求
- class Bicycle():
- def intro(self):
- print('我曾经跨过山河大海,也穿过人山人海~')
- def say(self):
- print('都有自行车了,要什么玛莎拉蒂?')
- b = Bicycle()
- animal(b)
复制代码 |
|