python object-oriented inheritance of

inherit

What is inherited

Inheritance is a way to create a new class, in python, the new class can inherit one or more parent classes, parent class can be called a base class or super class , the new class is called the derived class or subclass

python class inheritance is divided into: single and multiple inheritance

class ParentClass1: #定义父类
    pass

class ParentClass2: #定义父类
    pass

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

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

Tip: If you do not specify a base class, python class will inherit the default object class, object class is the base class for all python, which provides some common methods (such as __str__) implementation

>>> ParentClass1.__bases__
(<class 'object'>,)
>>> ParentClass2.__bases__
(<class 'object'>,)

Abstraction and inheritance (first abstract and then inherited)

Abstract i.e., extraction or like parts is more like.

Abstract is divided into two levels:

  1. Massey Obama and maybe more like objects into categories extracting portion;
  2. The humans, pigs, dogs three classes more like part of the extract into the parent class.

Abstract most important role is divided into categories (you can isolate concerns, reduce complexity)

img

Inheritance: is based on the abstract result, a programming language to implement it, certainly before undergoing the process of abstraction, in order to express the abstract structure by way of inheritance

Just an abstract process analysis and design, an action or a skill, you can get through abstract class

img

Inheritance and reusability

In the development program of the same process, if we define a class A, then you want to build another new class B, but like most of the content of the class A B

We can not start from scratch to write a class B, which uses the concept of inheritance of classes.

New Class B through inheritance, which allows the succession B A, B will 'genetic' all the attributes (data attribute and function attribute) of A, code reuse

Example: people and dogs Wars:

class Animal:  # 父类
    def __init__(self,hp,ad,name):
        self.hp = hp
        self.ad = ad
        self.name = name
    def eat(self):
        print('%s执行我啦'%self.name)
        self.hp += 5

class Person(Animal):
    def __init__(self,name,hp,ad,sex,job):
        self.sex = sex    # 人特有的
        self.job = job    # 人特有的
        Animal.__init__(self, hp, ad, name)
    def attack(self,dog):
        dog.hp -= self.ad
        print('%s攻击了%s,%s掉了%s点血'%(self.name,dog.name,dog.name,self.ad))

class Dog(Animal):
    def __init__(self,name,kind,hp,ad):   # 初始化方法
        Animal.__init__(self,hp,ad,name)  # 将父类的
        self.kind = kind  # kind是狗特有的
    def bite(self,person):
        person.hp -= self.ad
        print('%s咬了%s,%s掉了%s点血'%(self.name,person.name,person.name,self.ad))

二饼 = Dog('二饼','哈士奇',3000,150)
print(二饼.__dict__)
alex = Person('alex',100,5,'不详','乞丐')
print(alex.__dict__)

Tip: Use already have established a new class of class, thus reusing the software has some set most part, had greatly programming effort, it is often said that software reuse, not only can reuse your own class, others can also be inherited, such as standard libraries to customize the new data types, so is greatly reducing software development cycle of large software development is of great significance.

# A and B need to call the same method

# Create a parent class C, the same method into the class C

# A and B inherit CA (C) B (C)

Object # A and the object B can invoke methods on the direct C

# A and B have the same method, the same part of the functions, as well as different parts

# 创建父类C, 把相同的部分放到C类的方法中

# 在A\B中保留不同的部分,

# 然后分别在A\B中调用C类的方法即可

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

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

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

抽象类与接口类

接口类

继承有两种用途:

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

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

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)

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

class Payment:
    def pay(self):
        raise NotImplementedError

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


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

借用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() #不调就报错了

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

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

归一化使得高层的外部使用者可以不加区分的处理所有接口兼容的对象集合——就好象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 #定义抽象方法,无需实现功能
    def write(self):
        '子类必须定义写功能'
        pass

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

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

    def write(self):
        print('文本数据的读取方法')

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

    def write(self):
        print('硬盘数据的读取方法')

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

    def write(self):
        print('进程数据的读取方法')

wenbenwenjian=Txt()

yingpanwenjian=Sata()

jinchengwenjian=Process()

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

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

抽象类与接口类

抽象类的本质还是类,指一组类的相似性,包括数据属性和函数属性,而接口类强调只强调函数属性的相似性

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

在python并没有接口类这种东西,即使不通过专门的模块定义,也应该有一些概念

多继承问题

在继承抽象类的时候,尽量避免多继承

而在接口接口的时候,推荐多使用多继承

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

方法的实现

在抽象类中,我们可以对一些抽象方法,做出基本实现

而在接口类中,任何方法都只是一种规范,具体的功能需要子类的实现

super语法

super()函数是派生类用于继承父类(超类)的一个方法

super是用于解决多继承问题的,直接使用类名调用父类的方法在使用单继承时没问题,但如果涉及多继承,会出现问题,因为多继承会涉及到继承顺序(MRO),重复调用(钻石继承)等种种问题

MRO 就是类的方法解析顺序表,是一个列表,也是继承父类方法时的顺序表

  • 语法

    super().__init__(name)  # 第一种方法
    super(Student, self).__init__(name)  # 第二种方法
  • 实例

    class Course:
        course_lst = []
    def __init__(self,name,period,price):
            self.name = name
            self.period = period
            self.price = price
    
    class Role:
        def __init__(self,name):
            self.name = name
        def show_course(self):
            for item in Course.course_lst:
                print(item.name,item.period,item.price)
    
    class Student(Role):
        def __init__(self,name):
            # Role.__init__(self,name)
            # super(Student, self).__init__(name)
            super().__init__(name)   # super也可以帮助我们找到父类
            self.courses = []
    
    class Manager(Role):pass
    
    python = Course('python','6 months',19800)
    linux = Course('linux','5 months',17800)
    Course.course_lst = [python,linux]   # 所有的可选课程
    
    m = Student('alex')
    print(m.name)
    m.show_course()

钻石继承 && 多继承

继承顺序

img

img

class A:
    pass
    def func(self):
        print('in A')

class C(A):
    pass
    # def func(self):
    #     print('in C')

class B(A):
    pass
    # def func(self):
    #     print('in B')

class D(B):
    pass
    # def func(self):
    #     print('in D')
class E(C):
    pass
    # def func(self):
    #     print('in E')

class F(D,E):
    pass
    # def func(self):
    #     print('in F')
# f = F()
# f.func()
print(F.mro())  # 查看多继承中的继承顺序
# 顺序 遵循C3算法

#重新认识super
class D:
    def func(self):print('D')
class C(D):
    def func(self):
        super().func()
        print('C')
class B(D):
    def func(self):
        super().func()
        print('B')
class A(B,C):
    def func(self):
        super().func()
        print('A')

a = A()
a.func()

b = B()
b.func()
#新式类继承顺序: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.如果对下一个类存在两个合法的选择,选择第一个父类

继承小结

继承的作用

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

几个名词

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

抽象类与接口类

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


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

钻石继承

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

object类

object是python的默认类,有很多的方法,python种默认的list,str,dict等等都是继承了object类的方法

继承了object的类属于新式类 ,没有继承属于经典类

在python3种默认都是新式类,也即是所有的自定义类,基类都会继承object类

描述

在python3.x的所有类都是object的子类

所以对于一些内置的方法会写在object类中

如果子类不定义,在调用的时候最终会调用object类中的方法

就不会让程序出现不必要的错误了

__init__方法就是其中的一个例子

所有继承了object类的类 ---- 新式类

在python2中 不继承object类的都是 经典类

格式

class A(object):
    pass    # 新式类

class A:
    pass   # 经典类 :在多继承中遵循深度优先
           # 经典类中没有super和mro方法

总结

所有的py3中 的类都继承object 是新式类

在继承中 遵循 广度优先的 C3算法

You can also use mro to see the order of succession

super This method can help us find the next class in order mro

Guess you like

Origin www.cnblogs.com/Hybb/p/11518955.html