码迷,mamicode.com
首页 > 编程语言 > 详细

面向对象之继承——python篇

时间:2020-07-02 22:05:16      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:pre   默认   使用   student   sub   顺序查找   ini   super   __init__   

继承

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

父类,也被称为超类

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)

"""
C
bb
one
"""

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‘)
# BD

d = D()
d.show()
print(D.__mro__)
"""
A
C
B
D
(<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‘>)
    A
    D
    C
    B
    E
    F
    G
    """
    

对象相关的内置函数

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

    lass Person(object):
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    
    p1 = Person(‘张三‘, 18)
    p2 = Person(‘张三‘, 18)
    p3 = p1
    
    print(p1 is p2)  # False
    print(p1 is p3)  # True
    
  • isinstance:用来判断对象和类之间的关系

    class Person(object):
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    
    class Student(Person):
        def __init__(self, name, age, score):
            super(Student, self).__init__(name, age)
            self.score = score
    
    
    class Dog(object):
        def __init__(self, name, color):
            self.name = name
            self.color = color
    
    
    p = 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 = age
    
    
    class Student(Person):
        def __init__(self, name, age, score):
            super(Student, self).__init__(name, age)
            self.score = score
    
    
    class Dog(object):
        def __init__(self, name, color):
            self.name = name
            self.color = color
    
    
    print(issubclass(Student, Person))  # True
    print(issubclass(Dog, Person))  # False
    

运算符重载

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

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

from copy import copy


class 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)
"""
False
48
[{‘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篇

标签:pre   默认   使用   student   sub   顺序查找   ini   super   __init__   

原文地址:https://www.cnblogs.com/nongma-reddy/p/13226726.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!