面向对象之继承——python篇,,继承继承:让子类拥有


继承

继承:让子类拥有父类的所有属性和方法

父类,也被称为超类

python支持多继承,Java 不支持多继承,但支持多重继承。

类属性和方法的添加不会因为继承而受到任何影响。

对象属性是怎么被继承: 继承的时候因为__init__方法被继承,间接继承了对象属性。

在子类的__init__方法中通过supper()去调用父类的__init__的方法,实现继承。

类中的方法的调用过程

通过类或则对象在调用方法的时候,回先看当前类中有没有这个方法,如果有就直接调用自己类中;没有就看父类中有没有定义这个方法,如果父类定义了就用父类的,父类没有就再找父类的父类,直到找到最终父类object,object中没有才会报错。

多继承

子类可以拥有多个父类,并且具有所有父类的属性和方法。

子类只能继承一个父类的属性,方法只要不重名都能继承,重名只能继承第一个父类的方法。

继承其他的父类的属性,必须前面的父类没有__init__方法

class A:    def show(self):        print(‘hello‘)        print(‘A‘)class B():    def __init__(self, food):        self.food = food    def show(self):        print(‘B‘)    def bb(self):        print(‘bb‘)class C(A, B):    def __init__(self, food):        super(C, self).__init__(food)    def show(self):        print(‘C‘)# print(C.__mro__)c = C(‘one‘)c.show()c.bb()print(c.food)"""Cbbone"""

MRO

Python中针对类提供了一个内置属性__mro__可以用来查看方法的搜索顺序。MRO (Method Resolution Order,方法解析顺序)的简称,主要用于在多继承时判断方法属性的调用顺序。
print(C.__mro__)

在调用方法时,按照__mro__的输出结果从左至右的顺序查找。

如果再当前类中找到方法,就直接执行,不再向下搜索。

如果没有找到,就顺序查找下一个类中是否有对应的方法,如果找到,就直接执行,不再继续向下搜索。

如果找到了最后一个类,依然没有找到方法,程序就会报错。

super(类, 对象):? ?获取指定类的父类(对象必须是类的对象; 类默认指向当前类,对象默认是当前类的对象)

class A:    def show(self):        print(‘A‘)class B(A):    def show(self):        super(B, self).show()        print(‘B‘)class C(A):    def show(self):        super().show()        print(‘C‘)class D(B, C):    def show(self):        super().show()        print(‘D‘)# BDd = D()d.show()print(D.__mro__)"""ACBD(<class ‘__main__.D‘>, <class ‘__main__.B‘>, <class ‘__main__.C‘>, <class ‘__main__.A‘>, <class ‘object‘>)"""

mro扩展

class A:    def show(self):        print(‘A‘)class B(A):    def show(self):        super().show()        print(‘B‘)class C(A):    def show(self):        super().show()        print(‘C‘)class D(A):    def show(self):        super().show()        print(‘D‘)class E(B, C):    def show(self):        super().show()        print(‘E‘)class F(C, D):    def show(self):        super().show()        print(‘F‘)class G(F, E):    def show(self):        super().show()        print(‘G‘)print(G.__mro__)g = G()g.show()"""(<class ‘__main__.G‘>, <class ‘__main__.F‘>, <class ‘__main__.E‘>, <class ‘__main__.B‘>, <class ‘__main__.C‘>, <class ‘__main__.D‘>, <class ‘__main__.A‘>, <class ‘object‘>)ADCBEFG"""

对象相关的内置函数

身份运算符:判断两个对象是否相等 is

lass Person(object):    def __init__(self, name, age):        self.name = name        self.age = agep1 = Person(‘张三‘, 18)p2 = Person(‘张三‘, 18)p3 = p1print(p1 is p2)  # Falseprint(p1 is p3)  # True

isinstance:用来判断对象和类之间的关系

class Person(object):    def __init__(self, name, age):        self.name = name        self.age = ageclass Student(Person):    def __init__(self, name, age, score):        super(Student, self).__init__(name, age)        self.score = scoreclass Dog(object):    def __init__(self, name, color):        self.name = name        self.color = colorp = Person(‘tony‘, 18)s = Student(‘jack‘, 20, 90)d = Dog(‘旺财‘, ‘白色‘)print(isinstance(p, Person))  # True.对象p是由Person类创建出来的print(isinstance(s, Person))  # True.对象s是有Person类的子类创建出来的print(isinstance(d, Person))  # False.对象d和Person类没有关系

issubclass :用来判断两个类之间的继承关系

class Person(object):    def __init__(self, name, age):        self.name = name        self.age = ageclass Student(Person):    def __init__(self, name, age, score):        super(Student, self).__init__(name, age)        self.score = scoreclass Dog(object):    def __init__(self, name, color):        self.name = name        self.color = colorprint(issubclass(Student, Person))  # Trueprint(issubclass(Dog, Person))  # False

运算符重载

python中使用每一个运算符,其本质就是在调用运算符对应的方法(每个运算符都会调用对应的方法)

某种类型的数据支不支持某个运算符,就看这个数据对应的类型中有没有实现运算符对应的方法

from copy import copyclass Person:    def __init__(self, name=‘‘, age=0):        self.name = name        self.age = age    # +    def __add__(self, other):        # self + other        return self.age + other.age    # *    def __mul__(self, other):        list1 = []        for _ in range(other):            list1.append(copy(self))        return list1    # <    # 注意:大于符号和小于符号实现其中一个另外一个也可以用    def __lt__(self, other):        return self.age < other.age    def __repr__(self):        return f‘{str(self.__dict__)}‘p1 = Person(‘乌曼巴‘, age=18)p2 = Person(age=30)print(p1 == p2)print(p1 + p2)print(p1 * 3)print(p1 > p2)"""False48[{‘name‘: ‘乌曼巴‘, ‘age‘: 18}, {‘name‘: ‘乌曼巴‘, ‘age‘: 18}, {‘name‘: ‘乌曼巴‘, ‘age‘: 18}]False"""# 写了__lt__可以直接使用排序方法persons = [Person(‘乌曼巴‘, 20), Person(‘你诚心‘, 18), Person(‘得分手‘, 28), Person(‘李四‘, 15)]persons.sort()print(persons)"""[{‘name‘: ‘李四‘, ‘age‘: 15}, {‘name‘: ‘你诚心‘, ‘age‘: 18}, {‘name‘: ‘乌曼巴‘, ‘age‘: 20}, {‘name‘: ‘得分手‘, ‘age‘: 28}]"""

面向对象之继承——python篇

评论关闭