面向对象

面向对象 - 抽象类/多态: 
1.抽象类:只能被继承 不能被实例化
本质:是一个类 功能就是规范子类 基于继承演变而来的 通过抽象类把子类的标准规范起来
好处:降低使用者使用复杂度 统一标准
import abc metaclass=abc.ABCBeta @abc.abstractmethod 子类必须实现父类规定的方法

2.多态:同一类事物有多种形态:
eg:动物有多种形态 人 狗 猪
文件有多种形态 文本文件 可执行文件
多态的好处:
多态性:指的是可以在不考虑对象的类型的情况下而直接使用对象
动态多态性: p.run()
静态多态性: str int list 可相加+ str+str int+int
多态性的好处:
1.增加了程序的灵活性 -- 建立在多态的前提下
    以不变应万变,不论对象千变万化,使用者都是同一种形式去调用,如func(animal)
2.增加了程序的扩展性
  通过继承animal类创建了一个新的类,使用者无需更改自己的代码,还是用func(animal)去调用   

 1 import abc
 2 class Animal(metaclass=abc.ABCMeta):  # 同一类事物:动物
 3     all_type='animal'
 4     @abc.abstractmethod
 5     def run(self):
 6         pass
 7 
 8     @abc.abstractmethod
 9     def eat(self):
10         pass
11 
12 class People(Animal): # 动物的形态之一:人
13     s=123
14     def run(self):
15         print('people is running')
16 
17     def eat(self):
18         print('people is eatting')
19 
20     def func(self):
21         print('----------')
22 
23 class Pig(Animal): #动物的形态之二:狗
24     def run(self):
25         print('pig is running')
26 
27     def eat(self):
28         print('pig is eatting')
29 
30 # ani = Animal() # 不能实例化
31 p=People()
32 # p.run()
33 # p.func()
34 # print(p.s,p.all_type)
35 # pig=Pig()
36 # pig.run()
37 
38 # p.run()
39 # pig.run()
40 
41 # 不考虑对象的类型的情况下而直接使用对象
42 def func(animal):
43     animal.run()
44 
45 # func(p)
46 # func(pig)
多态

面向对象 - 鸭子类型:
python 崇尚鸭子类型
鸭子类型: 类与类之间不用共同继承父类,只要做的像同一种事物就ok
好处: 不继承父类 有共同的方法 给使用者带来直观性
之后: 使用者可以在不考虑对象类型的情况下 直接使用对象

 1 class Disk:
 2     def read(self):
 3         print('disk read')
 4 
 5     def write(self):
 6         print('disk write')
 7 
 8 class Text:
 9     def read(self):
10         print('text read')
11 
12     def write(self):
13         print('text write')
14 
15 disk=Disk()
16 text=Text()
17 
18 # disk.read()
19 # text.write()
20 
21 # eg:有序序列 list str tuple
22 li = list([1,2,3])
23 str=str('hello')
24 t=tuple(('a','b','c'))
25 
26 # print(len(li))
27 # print(len(str))
28 # print(len(t))
29 
30 def lens(obj):  # 不考虑对象类型的情况下 直接使用对象
31     return obj.__len__()
32 
33 # print(lens(li))
34 # print(lens(str))
35 # print(lens(t))
鸭子类型


原文地址:https://www.cnblogs.com/alice-bj/p/8545495.html