2022.08.17 DAY33
多态
- 多态是指同一个方法调用由于对象不同会产生不同的行为。
- 多态是方法的多态,属性没有多态。
- 多态的存在是有2个必要条件:继承、方法重写。
代码示例:
class Man:
def eat(self):
print('饿饿,饭饭...')
class Chinese(Man):
def eat(self):
print('中国人用筷子吃饭')
class English(Man):
def eat(self):
print('英国人用叉子吃饭')
class Indian(Man):
def eat(self):
print('印度人用手吃饭饭')
def manEat(m):
if isinstance(m, Man):
m.eat()
else:
print("不能吃饭...")
def test():
manEat(Man())
manEat(Chinese())
manEat(English())
manEat(Indian())
if __name__ == "__main__":
test()
运行结果:
饿饿,饭饭...
中国人用筷子吃饭
英国人用叉子吃饭
印度人用手吃饭饭
特殊方法和运算符的重载
-
Python的运算符实际上是通过调用对象的特殊方法实现的。
+ --- __add__ - --- __sub__ <, >=, == --- __it__, __le__, __eq__ >, >=, != --- __gt__, __ge__, __ne__ |, ^, & ----- __or__, __xor__, __and__ <<, >> ------ __lshift__, __rshift__ *, / -------- __mul__, __truediv__ %, // ------- __mod__, __floordiv__ ** ---------- __pow__
-
常见的特殊方法
__init__ 构造方法 __del__ 析构方法 __repr__, __str__ 打印,转换 __call__ 函数调用 __getattr__ 点号调用 __setattr__ 属性赋值 __getitem__ 索引运算 __setitem__ 索引赋值 __len__ 长度
实例:
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 "不是同类对象,故不能相加。"
def test():
P1 = Person("YJP")
P2 = Person("XX")
x = P1 + P2
print(x)
if __name__ == "__main__":
test()
结果:
YJP--XX