python -- 面向对象三大特性

1,继承

  1,初识继承

  什么是继承?

    ——继承是一种创建新类的方式,在 python 中,新建的类可以继承一个或多个父类,父类又可称为基类或超类,新建的类称为派生类或子类。

    子类会“遗传”父类的属性,从而解决代码重用的问题。

  python 中的继承分为:单继承和多继承

class ParentClass1: # 定义父类
    pass

class ParentClass2: # 定义父类
pass

class SubClass1(ParentClass1): # 单继承, 基类是 ParentClass1,派生类是 SubClass

<span style="color: rgba(0, 0, 255, 1)">pass</span>

class SubClass2(ParentClass1,ParentClass2): # python 支持多继承,用逗号分隔开多个继承的类

<span style="color: rgba(0, 0, 255, 1)">pass</span></pre>

  查看继承

>>> SubClass1.__bases__ #__base__ 只查看从左到右继承的第一个子类,__bases__ 则是查看所有继承的父类
(<class '__main__.ParentClass1'>,)
>>> SubClass2.__bases__
(<class '__main__.ParentClass1'>, <class '__main__.ParentClass2'>)

  经典类于新式类

1,只有在 python2 中才分新式类和经典类,python3 中统一都是新式类
2,在 python2 中,没有显示的继承 object 类的类,以及该类的子类,都是经典类
3,在 python2 中,显示的声明继承 object 的类,以及该类的子类,都是新式类
4,在 python3 中,无论是否继承 object,都是默认继承 object,即 python3 中所有的类都是新式类

在 python3 中,如果没有指定基类,python 的类会默认继承 object 类,object 是所有 python 中类的基类,它提供了一些常见的方法(如 __str__)的实现。用(__bases__)查看。

>>> ParentClass1.__bases__
(<class 'object'>,)
>>> ParentClass2.__bases__
(<class 'object'>,)
查看继承的类

 

  2,继承与抽象(先抽象再继承)

抽象就是抽取类似的,或者是比较像的部分。

抽象分成两个层次:

1. 将奥巴马和梅西这俩对象比较像的部分抽取成类; 

2. 将人,猪,狗这三个类比较像的部分抽取成父类。

抽象最主要的作用是划分类别(可以隔离关注点,降低复杂度)

 

  继承:是基于抽象的结果,通过编程语言取实现它,肯定是先经历抽象爱这个过程,才能通过继承的方式取表达出抽象的结构。

抽象只是分析和设计的过程中,一个动作或者说一种技巧,通过抽象可以得到类

 

  3,继承与重用性

  

class Animal:
    '''
    人和狗都是动物,所以创造一个 Animal 基类
    '''
    def __init__(self, name, aggressivity, life_value):
        self.name = name  # 人和狗都有自己的昵称;
        self.aggressivity = aggressivity  # 人和狗都有自己的攻击力;
        self.life_value = life_value  # 人和狗都有自己的生命值;
<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> eat(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">%s is eating</span><span style="color: rgba(128, 0, 0, 1)">'</span>%<span style="color: rgba(0, 0, 0, 1)">self.name)

class Dog(Animal):
'''
狗类,继承 Animal 类
'''
def bite(self, people):
'''
派生:狗有咬人的技能
:param people:
'''
people.life_value
-= self.aggressivity

class Person(Animal):
'''
人类,继承 Animal
'''
def attack(self, dog):
'''
派生:人有攻击的技能
:param dog:
'''
dog.life_value
-= self.aggressivity

egg = Person('egon',10,1000)
ha2
= Dog('二愣子',50,1000)
print(ha2.life_value)
print(egg.attack(ha2))
print(ha2.life_value)

使用继承来解决代码重用的例子

在开发程序的过程中,如果我们定义了一个类 A,然后又想新建立另一个类 B,但是类 B 的大部分内容与 A 类的相同时,我们不可能从头开始写一个类 B,这就用到了类的继承的概念。

通过继承的方式新疆类 B,让 B 继承 A,B 会“遗传”A 的所有属性(数据的属性和函数的属性),实现代码重用

class Hero:
    def __init__(self,nickname,aggressivity,life_value):
        self.nickname=nickname
        self.aggressivity=aggressivity
        self.life_value=life_value
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> move_forward(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">%s move forward</span><span style="color: rgba(128, 0, 0, 1)">'</span> %<span style="color: rgba(0, 0, 0, 1)">self.nickname)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> move_backward(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">%s move backward</span><span style="color: rgba(128, 0, 0, 1)">'</span> %<span style="color: rgba(0, 0, 0, 1)">self.nickname)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> move_left(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">%s move forward</span><span style="color: rgba(128, 0, 0, 1)">'</span> %<span style="color: rgba(0, 0, 0, 1)">self.nickname)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> move_right(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">%s move forward</span><span style="color: rgba(128, 0, 0, 1)">'</span> %<span style="color: rgba(0, 0, 0, 1)">self.nickname)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> attack(self,enemy):
    enemy.life_value</span>-=<span style="color: rgba(0, 0, 0, 1)">self.aggressivity

class Garen(Hero):
pass

class Riven(Hero):
pass

g1=Garen('草丛伦',100,300)
r1
=Riven('锐雯雯',57,200)

print(g1.life_value)
r1.attack(g1)
print(g1.life_value)

'''
运行结果
'''

View Code

提示:用已经有的类建立一个新类,这样就重用了已经有的软件中的一部分,大大减少了编程工作量,这就是常说的代码重用,不仅可以重用自己的类,也可以继承别人的,比如标准库,来定制新的数据类型,这样就大大缩短了软件开发周期,对大型软件开发来说,意义重大。

 

  4,派生

当然子类也可以添加自己新的属性或者在自己这里重新定义这些属性(不会影响到父类),需要注意的是,一旦重新定义了自己的属性且与父类重名,那么调用新增的属性时,就以自己为准了。

class Riven(Hero):
    camp='Noxus'
    def attack(self,enemy): #在自己这里定义新的 attack, 不再使用父类的 attack, 且不会影响父类
        print('from riven')
    def fly(self): #在自己这里定义新的
        print('%s is flying' %self.nickname)

在子类中,新建的重名的函数属性,在编辑函数内功能的时候,有可能需要重用父类中重名的那个函数功能,应该是用调用普通函数的方式,即:类名.func(),此时就与调用普通函数无异了,因此即便是 self 参数也要为其传值

class Riven(Hero):
    camp='Noxus'
    def __init__(self,nickname,aggressivity,life_value,skin):
        Hero.__init__(self,nickname,aggressivity,life_value) #调用父类功能
        self.skin=skin #新属性
    def attack(self,enemy): #在自己这里定义新的 attack, 不再使用父类的 attack, 且不会影响父类
        Hero.attack(self,enemy) #调用功能
        print('from riven')
    def fly(self): #在自己这里定义新的
        print('%s is flying' %self.nickname)

r1=Riven('锐雯雯',57,200,'比基尼')
r1.fly()
print(r1.skin)

'''
运行结果
锐雯雯 is flying
比基尼

View Code

在 python3 中,子类执行父类的方法也可以直接用 super 方法.

class A:
    def hahaha(self):
        print('A')

class B(A):
def hahaha(self):
super().hahaha()
#super(B,self).hahaha()
#A.hahaha(self)
print('B')

a = A()
b
= B()
b.hahaha()
super(B,b).hahaha()

super 方法
class Animal:
    '''
    人和狗都是动物,所以创造一个 Animal 基类
    '''
    def __init__(self, name, aggressivity, life_value):
        self.name = name  # 人和狗都有自己的昵称;
        self.aggressivity = aggressivity  # 人和狗都有自己的攻击力;
        self.life_value = life_value  # 人和狗都有自己的生命值;
<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> eat(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">%s is eating</span><span style="color: rgba(128, 0, 0, 1)">'</span>%<span style="color: rgba(0, 0, 0, 1)">self.name)

class Dog(Animal):
'''
狗类,继承 Animal 类
'''
def init(self,name,breed,aggressivity,life_value):
super().
init(name, aggressivity, life_value) #执行父类 Animal 的 init 方法
self.breed = breed #派生出了新的属性

<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> bite(self, people):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">
    派生出了新的技能:狗有咬人的技能
    :param people:  
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(0, 0, 0, 1)">
    people.life_value </span>-=<span style="color: rgba(0, 0, 0, 1)"> self.aggressivity

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> eat(self):
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> Animal.eat(self)</span>
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">super().eat()</span>
    <span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">from Dog</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

class Person(Animal):
'''
人类,继承 Animal
'''
def init(self,name,aggressivity, life_value,money):
#Animal.init(self, name, aggressivity, life_value)
#super(Person, self).init(name, aggressivity, life_value)
super().init(name,aggressivity, life_value) #执行父类的 init 方法
self.money = money #派生出了新的属性

<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> attack(self, dog):
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(128, 0, 0, 1)">
    派生出了新的技能:人有攻击的技能
    :param dog: 
    </span><span style="color: rgba(128, 0, 0, 1)">'''</span><span style="color: rgba(0, 0, 0, 1)">
    dog.life_value </span>-=<span style="color: rgba(0, 0, 0, 1)"> self.aggressivity

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> eat(self):
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">super().eat()</span>

Animal.eat(self)
print('from Person')

egg = Person('egon',10,1000,600)
ha2
= Dog('二愣子','哈士奇',10,1000)
print(egg.name)
print(ha2.name)
egg.eat()

View Code

通过继承建立了派生类与基类之间的关系,它是一种“是”的关系,比如白马是马,人是动物。

当类之间有有许多相同的功能,提取这些相同的功能做成基类,用继承比较好,比如教授是老师

class Teacher:
    def __init__(self,name,gender):
        self.name = name
        self.gender = gender
    def teach(self):
        print("teaching")

class Professor(Teacher):
pass
p1
= Professor("egon","male")
p1.teach()
"""
运行结果 >>>teaching
"""

View Code

 

5,抽象类与接口类

  接口类

继承有两种用途:

一:继承基类的方法,并且做出自己的改变或扩展(代码重用)

二:声明某个子类兼容于某基类,定义一个接口类 lnterface, 接口类中定义了一些接口名(就是函数名)且并未实现接口的功能,子类继承接口类,并且实现接口中的功能

class Alipay:
    '''
    支付宝支付
    '''
    def pay(self,money):
        print('支付宝支付了 %s 元'%money)

class Applepay:
'''
apple pay 支付
'''
def pay(self,money):
print('apple pay 支付了 %s 元'%money)

def pay(payment,money):
'''
支付函数,总体负责支付
对应支付的对象和要支付的金额
'''
payment.pay(money)

p = Alipay()
pay(p,
200)

View Code

开发中容易出现的问题:

class Alipay:
    '''
    支付宝支付
    '''
    def pay(self,money):
        print('支付宝支付了 %s 元'%money)

class Applepay:
'''
apple pay 支付
'''
def pay(self,money):
print('apple pay 支付了 %s 元'%money)

class Wechatpay:
def fuqian(self,money):
'''
实现了 pay 的功能,但是名字不一样
'''
print('微信支付了 %s 元'%money)

def pay(payment,money):
'''
支付函数,总体负责支付
对应支付的对象和要支付的金额
'''
payment.pay(money)

p = Wechatpay()
pay(p,
200) #执行会报错

View Code

接口初成:手动报异常:NotImplementedError 来解决开发中遇到的问题

class Payment:
    def pay(self):
        raise NotImplementedError

class Wechatpay(Payment):
def fuqian(self,money):
print('微信支付了 %s 元'%money)

p = Wechatpay() #这里不报错
pay(p,200) #这里报错了

View Code

借用 abc 模块来实现接口

from abc import ABCMeta,abstractmethod

class Payment(metaclass=ABCMeta):
@abstractmethod
def pay(self,money):
pass

class Wechatpay(Payment):
def fuqian(self,money):
print('微信支付了 %s 元'%money)

p = Wechatpay() #不调就报错了

View Code
# 工作中 公司有使用抽象类开发的规则
# 源码 别人使用抽象类

# 支付功能
from abc import ABCMeta,abstractmethod

class Payment(metaclass=ABCMeta): # 模板的功能
@abstractmethod # abstractmethod 是一个装饰器,装饰器怎么用?放在函数 / 类的上一行
def pay(self):pass

@abstractmethod
</span><span style="color: rgba(0, 0, 255, 1)">def</span> shouqian(self):<span style="color: rgba(0, 0, 255, 1)">pass</span>

class Alipay(Payment):
def pay(self,money):
print('使用支付宝支付了 %s 元'%money)

class Wechatpay(Payment):
def pay(self,money):
print('使用微信支付了 %s 元'%money)

class ApplePay(Payment):
def pay(self,money):
print('使用 applepay 支付了 %s 元' % money)

def pay(obj,money):
obj.pay(money)

p = Payment()
# a = Alipay()
#
# a.pay(100)
#
pay(a,100)

# we = Wechatpay()
#
# we.pay(200)
#
pay(we,200)

# ap = ApplePay()

# 规范
#
多人开发、复杂的需求、后期的扩展
#
手段 来帮助我们完成规范

# 抽象类
# 抽象类是一个规范,它基本不会实现什么具体的功能,抽象类是不能被实例化
# 要想写一个抽象类
# from abc import ABCMeta,abstractmethod
# 在这个类创建的时候指定 metaclass = ABCMeta
# 在你希望子类实现的方法上加上一个 @abstractmethod 装饰器
# 使用抽象类
# 继承这个类
# 必须实现这个类中被 @abstractmethod 装饰器装饰的方法

规范

 

实践中,继承的第一种含义意义并不很大,甚至常常是有害的。因为它使得子类与基类出现强耦合。

继承的第二种含义非常重要。它又叫“接口继承”。
接口继承实质上是要求“做出一个良好的抽象,这个抽象规定了一个兼容接口,使得外部调用者无需关心具体细节,可一视同仁的处理实现了特定接口的所有对象”——这在程序设计上,叫做归一化。

归一化使得高层的外部使用者可以不加区分的处理所有接口兼容的对象集合——就好象 linux 的泛文件概念一样,所有东西都可以当文件处理,不必关心它是内存、磁盘、网络还是屏幕(当然,对底层设计者,当然也可以区分出“字符设备”和“块设备”,然后做出针对性的设计:细致到什么程度,视需求而定)。

依赖倒置原则:
高层模块不应该依赖低层模块,二者都应该依赖其抽象;抽象不应该应该依赖细节;细节应该依赖抽象。换言之,要针对接口编程,而不是针对实现编程

在 python 中根本就没有一个叫做 interface 的关键字,上面的代码只是看起来像接口,其实并没有起到接口的作用,子类完全可以不用去实现接口 ,如果非要去模仿接口的概念,可以借助第三方模块:

http://pypi.python.org/pypi/zope.interface

twisted的 twisted\internet\interface.py 里使用 zope.interface

文档 https://zopeinterface.readthedocs.io/en/latest/

设计模式:https://github.com/faif/python-patterns

接口提取了一群类共同的函数,可以把接口当做一个函数的集合。

然后让子类去实现接口中的函数。

这么做的意义在于归一化,什么叫归一化,就是只要是基于同一个接口实现的类,那么所有的这些类产生的对象在使用时,从用法上来说都一样。

归一化,让使用者无需关心对象的类是什么,只需要的知道这些对象都具备某些功能就可以了,这极大地降低了使用者的使用难度。

比如:我们定义一个动物接口,接口里定义了有跑、吃、呼吸等接口函数,这样老鼠的类去实现了该接口,松鼠的类也去实现了该接口,由二者分别产生一只老鼠和一只松鼠送到你面前,即便是你分别不到底哪只是什么鼠你肯定知道他俩都会跑,都会吃,都能呼吸。

再比如:我们有一个汽车接口,里面定义了汽车所有的功能,然后由本田汽车的类,奥迪汽车的类,大众汽车的类,他们都实现了汽车接口,这样就好办了,大家只需要学会了怎么开汽车,那么无论是本田,还是奥迪,还是大众我们都会开了,开的时候根本无需关心我开的是哪一类车,操作手法(函数调用)都一样

为何要用接口

  抽象类

什么是抽象类?

  --  与 java 一样,python 也有抽象类的概念但是同样需要借助模块实现,抽象类是一个特殊的类,它的特殊之处在于只能被继承,不能被实例化

为什么要有抽象类?

  -- 如果说类是从一堆对象中抽取相同的内容而来的,那么抽象类是从一堆中抽取相同的内容而来的,内容包括数据属性和函数属性。

  

比如我们有香蕉的类,有苹果的类,有桃子的类,从这些类抽取相同的内容就是水果这个抽象的类,你吃水果时,要么是吃一个具体的香蕉,要么是吃一个具体的桃子。。。。。。你永远无法吃到一个叫做水果的东西。

    从设计角度去看,如果类是从现实对象抽象而来的,那么抽象类就是基于类抽象而来的。

  从实现角度来看,抽象类与普通类的不同之处在于:抽象类中有抽象方法,该类不能被实例化,只能被继承,且子类必须实现抽象方法。这一点与接口有点类似,但其实是不同的,即将揭晓答案

在 python 中实现抽象类:

#一切皆文件
import abc #利用 abc 模块实现抽象类

class All_file(metaclass=abc.ABCMeta):
all_type
='file'
@abc.abstractmethod
#定义抽象方法,无需实现功能
def read(self):
'子类必须定义读功能'
pass

@abc.abstractmethod </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">定义抽象方法,无需实现功能</span>
<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> write(self):
    </span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">子类必须定义写功能</span><span style="color: rgba(128, 0, 0, 1)">'</span>
    <span style="color: rgba(0, 0, 255, 1)">pass</span>

# class Txt(All_file):
#
pass

# t1=Txt() #报错, 子类没有定义抽象方法

class Txt(All_file): #子类继承抽象类,但是必须定义 read 和 write 方法
def read(self):
print('文本数据的读取方法')

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> write(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">文本数据的读取方法</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

class Sata(All_file): #子类继承抽象类,但是必须定义 read 和 write 方法
def read(self):
print('硬盘数据的读取方法')

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> write(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">硬盘数据的读取方法</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

class Process(All_file): #子类继承抽象类,但是必须定义 read 和 write 方法
def read(self):
print('进程数据的读取方法')

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> write(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">进程数据的读取方法</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

wenbenwenjian=Txt()

yingpanwenjian=Sata()

jinchengwenjian=Process()

#这样大家都是被归一化了, 也就是一切皆文件的思想
wenbenwenjian.read()
yingpanwenjian.write()
jinchengwenjian.read()

print(wenbenwenjian.all_type)
print(yingpanwenjian.all_type)
print(jinchengwenjian.all_type)

View Code

抽象类与接口类:

抽象类的本质还是类,指的是一组类的相似性,包括数据属性(如 all_type)和函数属性(如 read、write),而接口只强调函数属性的相似性。

抽象类是一个介于类和接口直接的一个概念,同时具备类和接口的部分特性,可以用来实现归一化设计 

在 python 中,并没有接口类这种东西,即便不通过专门的模块定义接口,我们也应该有一些基本的概念。

  1. 多继承问题

在继承抽象类的过程中,我们应该尽量避免多继承;
而在继承接口的时候,我们反而鼓励你来多继承接口

接口隔离原则:
使用多个专门的接口,而不使用单一的总接口。即客户端不应该依赖那些不需要的接口。

  2,方法的实现

在抽象类中,我们可以对一些抽象方法做出基础实现;
而在接口类中,任何方法都只是一种规范,具体的功能需要子类实现

 

6,钻石继承

  继承顺序

  

class A(object):
    def test(self):
        print('from A')

class B(A):
def test(self):
print('from B')

class C(A):
def test(self):
print('from C')

class D(B):
def test(self):
print('from D')

class E(C):
def test(self):
print('from E')

class F(D,E):
# def test(self):
# print('from F')
pass
f1
=F()
f1.test()
print(F.mro) #只有新式才有这个属性可以查看线性列表,经典类没有这个属性

#新式类继承顺序:F->D->B->E->C->A
#
经典类继承顺序:F->D->B->A->E->C
#
python3 中统一都是新式类
#
pyhon2 中才分新式类与经典类

顺序

 

 

 

  继承原理

python 到底是如何实现继承的,对于你定义的每一个类,python 会计算出一个方法解析顺序 (MRO) 列表,这个 MRO 列表就是一个简单的所有基类的线性顺序列表,例如

>>> F.mro() #等同于 F.__mro__
[<class '__main__.F'>, <class '__main__.D'>, <class '__main__.B'>, <class '__main__.E'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]

 

为了实现继承,python 会在 MRO 列表上从左到右开始查找基类, 直到找到第一个匹配这个属性的类为止。
而这个 MRO 列表的构造是通过一个 C3 线性化算法来实现的。我们不去深究这个算法的数学原理, 它实际上就是合并所有父类的 MRO 列表并遵循如下三条准则:
1. 子类会先于父类被检查
2. 多个父类会根据它们在列表中的顺序被检查
3. 如果对下一个类存在两个合法的选择, 选择第一个父类

 

7,继承小结

继承的作用

减少代码的重用
提高代码可读性
规范编程模式

几个名词

抽象:抽象即抽取类似或者说比较像的部分。是一个从具题到抽象的过程。
继承:子类继承了父类的方法和属性
派生:子类在父类方法和属性的基础上产生了新的方法和属性

抽象类接口

1. 多继承问题
在继承抽象类的过程中,我们应该尽量避免多继承;
而在继承接口的时候,我们反而鼓励你来多继承接口

2. 方法的实现
在抽象类中,我们可以对一些抽象方法做出基础实现;
而在接口类中,任何方法都只是一种规范,具体的功能需要子类实现

钻石继承

新式类:广度优先
经典类:深度优先

 

2,多态

多态指的是一类事物有多种形态

动物有多种形态:人,猪,狗

import abc
class Animal(metaclass=abc.ABCMeta): #同一类事物: 动物
    @abc.abstractmethod
    def talk(self):
        pass

class People(Animal): #动物的形态之一: 人
def talk(self):
print('say hello')

class Dog(Animal): #动物的形态之二: 狗
def talk(self):
print('say wangwang')

class Pig(Animal): #动物的形态之三: 猪
def talk(self):
print('say aoao')

文件有多种形态:文本文件,可执行文件

import abc
class File(metaclass=abc.ABCMeta): #同一类事物: 文件
    @abc.abstractmethod
    def click(self):
        pass

class Text(File): #文件的形态之一: 文本文件
def click(self):
print('open file')

class ExeFile(File): #文件的形态之二: 可执行文件
def click(self):
print('execute file')

  1,多态性

什么是多态动态绑定(在继承的背景下使用,有时也称为多态性)

  -- 多态性是指在不考虑实例的情况下使用实例

在面向对象方法中一般是这样表述多态性:
向不同的对象发送同一条消息(!!!obj.func(): 是调用了 obj 的方法 func,又称为向 obj 发送了一条消息 func),不同的对象在接收时会产生不同的行为(即方法)。
也就是说,每个对象可以用自己的方式去响应共同的消息。所谓消息,就是调用函数,不同的行为就是指不同的实现,即执行不同的函数。

比如:老师. 下课铃响了(),学生. 下课铃响了 (),老师执行的是下班操作,学生执行的是放学操作,虽然二者消息一样,但是执行的效果不同

peo=People()
dog=Dog()
pig=Pig()

#peo、dog、pig 都是动物, 只要是动物肯定有 talk 方法
#
于是我们可以不用考虑它们三者的具体是什么类型, 而直接使用
peo.talk()
dog.talk()
pig.talk()

#更进一步, 我们可以定义一个统一的接口来使用
def func(obj):
obj.talk()

多态性

 

  鸭子类型

逗比时刻:

  Python 崇尚鸭子类型,即‘如果看起来像、叫声像而且走起路来像鸭子,那么它就是鸭子’

python 程序员通常根据这种行为来编写程序。例如,如果想编写现有对象的自定义版本,可以继承该对象

也可以创建一个外观和行为像,但与它无任何关系的全新对象,后者通常用于保存程序组件的松耦合度。

例 1:利用标准库中定义的各种‘与文件类似’的对象,尽管这些对象的工作方式像文件,但他们没有继承内置文件对象的方法

例 2:序列类型有多种形态:字符串,列表,元组,但他们直接没有直接的继承关系

#二者都像鸭子, 二者看起来都像文件, 因而就可以当文件一样去用
class TxtFile:
    def read(self):
        pass
<span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> write(self):
    </span><span style="color: rgba(0, 0, 255, 1)">pass</span>

class DiskFile:
def read(self):
pass
def write(self):
pass

再如 len() 方法,字符串,列表,元组,能用,而 int,dict 不能用

 

3,封装

封装:隐藏对象的属性和实现细节,仅对外提供公共访问方式。

好处:

1. 将变化隔离; 

2. 便于使用;

3. 提高复用性; 

4. 提高安全性;

封装原则:

  1,将不需要对外提供的内容都隐藏起来,

  2,把属性都隐藏,提供公共方法对其访问。

  1,私有变量和私有方法

在 python 中用双下划线开头的方式将属性隐藏起来(设置成私有的)

私有变量

#其实这仅仅这是一种变形操作
#类中所有双下划线开头的名称如 __x 都会自动变形成:_ 类名 __x 的形式:

class A:
__N=0 #类的数据属性就应该是共享的, 但是语法上是可以把类的数据属性设置成私有的如 __N, 会变形为 _A__N
def init(self):
self.
__X=10 #变形为 self._A__X
def __foo(self): #变形为 _A__foo
print('from A')
def bar(self):
self.
__foo() #只有在类内部才可以通过 __foo 的形式访问到.

#A._A__N 是可以访问到的,即这种操作并不是严格意义上的限制外部访问,仅仅只是一种语法意义上的变形

这种自动变形的特点:

1. 类中定义的__x 只能在内部使用,如 self.__x,引用的就是变形的结果

2. 这种变形其实正是针对外部的变形,在外部是无法通过 __x 这个名字访问到的。

3. 在子类定义的 __x 不会覆盖在父类定义的 __x,因为子类中变形成了:_ 子类名 __x, 而父类中变形成了:_ 父类名 __x,即双下滑线开头的属性在继承给子类时,子类是无法覆盖的。

 

这种变形需要注意的问题是:

1. 这种机制也并没有真正意义上限制我们从外部直接访问属性,知道了类名和属性名就可以拼出名字:_ 类名 __ 属性,然后就可以访问了,如 a._A__N

2. 变形的过程只在类的内部生效, 在定义后的赋值操作,不会变形

 

 私有方法

3,在继承中,父类如果不想让子类覆盖自己的方法,可以将方法定义为私有的

#正常情况
class A:
    def fa(self):
        print("from a")
    def test(self):
        self.fa()
class B(A):
    def fa(self):
        print("from b")
b = B()b.test()
>>> from b

#把 fa 定义成私有的,即 __fa
class A:
def __fa(self): #在定义时就变形为 _A__fa
print("from a")
def test(self):
self.
__fa() #只会与自己所在的类为准, 即调用 _A__fa
class B(A):
def __fa(self):
print("from b")
b
= B()
b.test()
>>>from a

小结

1, 我为什么要定义一个私有变量呢:
     我不想让你看到这个值
     我不想让你修改这个值
     我想让你在修改这个值得时候有一些限制
     有些方法或者属性不希望被子类继承

2,私有变量不能在外部被定义

3,私有变量不能被继承

4, 广义上的封装 把属性函数都放到类里
狭义上的封装 定义私有成员

5, 类中的私有成员:
私有的静态属性
私有的对象属性
私有的方法

6, 我为什么要定义一个私有变量呢:
# 我不想让你看到这个值
# 我不想让你修改这个值
# 我想让你在修改这个值得时候有一些限制 : 保证了数据的安全
# 有些方法或者属性不希望被子类继承

 

封装与扩展性

封装在于明确区分内外,使得类实现者可以修改封装内的东西而不影响外部调用者的代码;而外部使用用者只知道一个接口 (函数),只要接口(函数)名、参数不变,使用者的代码永远无需改变。这就提供一个良好的合作基础——或者说,只要接口这个基础约定不变,则代码改变不足为虑。

#类的设计者
class Room:
    def __init__(self,name,owner,width,length,high):
        self.name=name
        self.owner=owner
        self.__width=width
        self.__length=length
        self.__high=high
    def tell_area(self): #对外提供的接口,隐藏了内部的实现细节,此时我们想求的是面积
        return self.__width * self.__length

#使用者
>>> r1=Room('卧室','egon',20,20,20)
>>> r1.tell_area() #使用者调用接口 tell_area

#类的设计者,轻松的扩展了功能,而类的使用者完全不需要改变自己的代码
class Room:
def init(self,name,owner,width,length,high):
self.name
=name
self.owner
=owner
self.
__width=width
self.
__length=length
self.
__high=high
def tell_area(self): #对外提供的接口,隐藏内部实现,此时我们想求的是体积, 内部逻辑变了, 只需求修该下列一行就可以很简答的实现, 而且外部调用感知不到, 仍然使用该方法,但是功能已经变了
return self.__width * self.__length * self.__high

#对于仍然在使用 tell_area 接口的人来说,根本无需改动自己的代码,就可以用上新功能
>>> r1.tell_area()

 

 property 属性

 什么是特性 property

property 是一种特殊的属性,访问它时会执行一段功能(函数 ) 然后返回值

"""
例一:BMI 指数(bmi 是计算而来的,但很明显它听起来像是一个属性而非方法,如果我们将其做成一个属性,更便于理解)

成人的 BMI 数值:
过轻:低于 18.5
正常:18.5-23.9
过重:24-27
肥胖:28-32
非常肥胖, 高于 32
  体质指数(BMI)= 体重(kg)÷身高 ^2(m)
  EX:70kg÷(1.75×1.75)=22.86

"""
class People:
def init(self,name,weight,height):
self.name
=name
self.weight
=weight
self.height
=height
@property
def bmi(self):
return self.weight / (self.height**2)

p1=People('egon',75,1.85)
print(p1.bmi)

例一
import math
class Circle:
    def __init__(self,radius): #圆的半径 radius
        self.radius=radius
@property
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> area(self):
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> math.pi * self.radius**2 <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">计算面积</span>
@property def perimeter(self): return 2*math.pi*self.radius #计算周长 c=Circle(10) print(c.radius) print(c.area) #可以向访问数据属性一样去访问 area, 会触发一个函数的执行, 动态计算出一个值 print(c.perimeter) #同上 ''' 输出结果: 314.1592653589793 62.83185307179586 ''' ***** #注意:此时的特性 area 和 perimeter 不能被赋值 c.area=3 #为特性 area 赋值 ''' 抛出异常: AttributeError: can't set attribute '''
例二

为什么要用 property

将一个类的函数定义成特性以后,对象再去使用的时候 obj.name, 根本无法察觉自己的 name 是执行了一个函数然后计算出来的,这种特性的使用方式遵循了统一访问的原则

除此之外,看下

ps:面向对象的封装有三种方式:
【public】
这种其实就是不封装, 是对外公开的
【protected】
这种封装方式对外不公开, 但对朋友 (friend) 或者子类 (形象的说法是“儿子”, 但我不知道为什么大家 不说“女儿”, 就像“parent”本来是“父母”的意思, 但中文都是叫“父类”) 公开
【private】
这种封装对谁都不公开

python 并没有在语法上把它们三个内建到自己的 class 机制中,在 C++ 里一般会将所有的数据都设为私有,然后提供 set 和 get 方法(接口)去设置和获取,在 python 中通过 property 方法可以实现

class Foo:
    def __init__(self,val):
        self.__NAME=val #将所有的数据属性都隐藏起来

    @property
    def name(self):
        return self.__NAME #obj.name 访问的是 self.__NAME(这也是真实值的存放位置)

    @name.setter
    def name(self,value):
        if not isinstance(value,str):  #在设定值之前进行类型检查
            raise TypeError('%s must be str' %value)
        self.__NAME=value #通过类型检查后, 将值 value 存放到真实的位置 self.__NAME

    @name.deleter
    def name(self):
        raise TypeError('Can not delete')

f=Foo('egon')
print(f.name)
# f.name=10 #抛出异常 'TypeError: 10 must be str'
del f.name #抛出异常 'TypeError: Can not delete'

View Code

一个静态属性 property 本质就是实现了 get,set,delete 三种方法

class Foo:
    @property
    def AAA(self):
        print('get 的时候运行我啊')
@AAA.setter
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> AAA(self,value):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">set的时候运行我啊</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

@AAA.deleter
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> AAA(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">delete的时候运行我啊</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

#只有在属性 AAA 定义 property 后才能定义 AAA.setter,AAA.deleter
f1=Foo()
f1.AAA
f1.AAA
='aaa'
del f1.AAA

View Code
class Foo:
    def get_AAA(self):
        print('get 的时候运行我啊')
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> set_AAA(self,value):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">set的时候运行我啊</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)

</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> delete_AAA(self):
    </span><span style="color: rgba(0, 0, 255, 1)">print</span>(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">delete的时候运行我啊</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
AAA</span>=property(get_AAA,set_AAA,delete_AAA) <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)">内置property三个参数与get,set,delete一一对应</span>
f1=Foo() f1.AAA f1.AAA='aaa' del f1.AAA
View Code

怎么用?

class Goods:
</span><span style="color: rgba(0, 0, 255, 1)">def</span> <span style="color: rgba(128, 0, 128, 1)">__init__</span><span style="color: rgba(0, 0, 0, 1)">(self):
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 原价</span>
    self.original_price = 100
    <span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 折扣</span>
    self.discount = 0.8<span style="color: rgba(0, 0, 0, 1)">

@property
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> price(self):
    </span><span style="color: rgba(0, 128, 0, 1)">#</span><span style="color: rgba(0, 128, 0, 1)"> 实际价格 = 原价 * 折扣</span>
    new_price = self.original_price *<span style="color: rgba(0, 0, 0, 1)"> self.discount
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> new_price

@price.setter
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> price(self, value):
    self.original_price </span>=<span style="color: rgba(0, 0, 0, 1)"> value

@price.deleter
</span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> price(self):
    </span><span style="color: rgba(0, 0, 255, 1)">del</span><span style="color: rgba(0, 0, 0, 1)"> self.original_price

obj = Goods()
obj.price
# 获取商品价格
obj.price = 200 # 修改商品原价
print(obj.price)
del obj.price # 删除商品原价

View Code