课时113
#测试重写object的_str_()
class Person:
def __init__(self,name):
self.name=name
def __str__(self):
return "名字是{0}".format(self.name)
p=Person("老三")
print(p)
执行结果:
名字是老三
?课时114
?课时115
?
#测试mro()函数
class A:
def aa(self):
print("aa")
def say(self):
print("say AAA")
class B:
def bb(self):
print("bb")
def say(self):
print("say BBB")
class C(B,A):
def cc(self):
print("cc")
c=C()
print(C.mro())
c.say()
执行结果:
[<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
say BBB
?课时116
#测试supper()
class A:
def say(self):
print("A:",self)
class B(A):
def say(self):
super().say()#也可以直接调用A.say(self)
print("B:",self)
B().say()
执行结果:
A: <__main__.B object at 0x0000015B824C4E88>
B: <__main__.B object at 0x0000015B824C4E88>
?课时117
#多态
class Man:
def hungry(self):
print("想吃炸鸡")
class Chinese(Man):
def hungry(self):
print("配上奶香芝士")
class People(Man):
def hungry(self):
print("蜂蜜芥末也行")
def Eat(a):
if isinstance(a,Man):
a.hungry()
else:
print("不能吃!")
Eat(Chinese())
Eat(People())
执行结果:
配上奶香芝士
蜂蜜芥末也行
?
?
|