类和对象-Ⅵ
>>> # 多态>>> 3 + 5
8
>>> "Py" + "thon"
'Python'
>>> len("FishC")
5
>>> len("Python", "FichC", "Me")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: len() takes exactly one argument (3 given)
>>> len(["Python", "FichC", "Me"])
3
>>> len({"name":"小甲鱼", "age":"18"})
2
>>> 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)
>>> s.name
'正方形'
>>> c.name
'圆形'
>>> t.name
'三角形'
>>> s.area()
25
>>> c.area()
113.03999999999999
>>> t.area()
6.0
>>> # 正方形、圆形、三角形都继承自 Shape 类,但又都重写了构造函数和 area() 方法,这就是多态的体现。
>>> # 自定义函数的多态
>>> class Cat:
... def __init__(self, name, age):
... self.name = name
... self.age = age
... def intro(self):
... print(f"我是一直沙雕猫咪,我叫{self.name}, 今年{self.age}岁~")
...
>>> 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("哟吼")
...
>>> 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)
我是一只沙雕猫咪,我叫web, 今年4岁~
mua~
>>> animal(d)
我是一只小狗,我叫布布, 今年7岁~
哟吼
>>> animal(p)
我是一只小猪,我叫大肠, 今年5岁~
oink~
>>> # animal() 函数就具有多态性,该函数接收不同对象作为参数,并在不检查其类型的情况下执行其方法。
>>> class Bicycle:
... def intro(self):
... print("我曾经跨过山和大海,也穿过人山人海~")
... def say(self):
... print("都有自行车了,要什么兰博基尼~")
...
>>> b = Bicycle()
>>> animal(b)
我曾经跨过山和大海,也穿过人山人海~
都有自行车了,要什么兰博基尼~
页:
[1]