多态
同一个方法由于对象不同产生不同的行为
注意:
1 多态是方法的多态,属性没没有多态
2 多态的存在有两个必要条件:继承和方法重写
class Man:
def eat(self):
print("eat")
class Chinese(Man):
def eat(self):
print("用筷子")
class English(Man):
def eat(self):
print("用叉子")
def manEat(M):
if isinstance(M, Man): # 判断M是不是Man的子类
M.eat()
else:
print("not eat")
manEat(Chinese()) # 返回值为 用筷子
manEat(English()) # 返回值为 用叉子
特殊方法和运算符重载
特殊方法:
运算符重载:
class Person:
def __init__(self, name):
self.name = name
def __add__(self, other):
if (isinstance(other, Person)):
return "{0}->{1}".format(self.name, other.name)
else:
return "error"
p1 = Person("ZS")
p2 = Person("LS")
X = p1 + p2 # 如果不重新定义add方法,会报错
print(X)