day_013 Python中的面对对象补充

2018-08-02  本文已影响0人  HavenYoung

一、重写

继承后,子类可以拥有除父类继承以外的其他属性和方法
父类不能使用在子类中添加的属性和方法
1.关于方法
a.在子类中可以添加其他的方法
b.重写:
1)完全重写
重新实现从父类继承下来的方法,重写后,子类再调用这个方法的时候,就调用子类的

2)保留父类实现的类容,再添加新的功能

对象和类调用方法的过程:先看当前类是否有这个方法,没有才去查看父又没有相应的方法,如果父类没有就看父类的父类,直到找到基类(object)为止

示例:

class Animal(object):
    """动物类"""

    def __init__(self):
        self.age = 0
        self.color = ''

    def eat(self):
        print('eating~~~')

    def shout(self):
        print('barking')

    @classmethod
    def get_number(cls):
        return  100


class Dog(Animal):
    """狗类"""

    def look_after(self):
        print('看家')

    # 重写父类的shout
    def shout(self):
        print('啊汪')

    def eat(self):
        # 保留父类eat的功能
        super().eat()
        print('bone')

    @classmethod
    def get_number(cls):
        # 保留父类的类方法的功能的时候,还是super().类方法
        print(super().get_number())


if __name__ == '__main__':
    dog = Dog()
    dog.age = 2
    print(dog.color)
    dog.shout()
    dog.look_after()

结果:

啊汪
看家

二、添加属性

对象属性的继承方法:是通过继承init方法来继承的对象属性

给当前类添加对象属性:重写init方法,注意:如果要保留父类的属性,需要使用super().init方法

三、运算符的重载

1.重载:一个类中可以有多个名字相同的方法,就叫重载。python中不支持
2.运算符重载(重新定义运算符运算的过程)
>、<、+、-
大于和小于符号只需要重载其中的一个,另外一个的结果,直接是重载的结果取反

示例:

class Student:
    def __init__(self, name='', age=0, height=0):
        self.name = name
        self.age = age
        self.height = height

    # 重载:>
    """
    self > other
    """
    def __gt__(self, other):
        # 比较对象1>对象2的时候是比较的他们的height属性
        return self.height > other.height

    # 重载:<
    def __lt__(self, other):
        return self.age < other.age

    # 重载:+
    def __add__(self, other):
        return self.age + other.age

    # 重载:-
    def __sub__(self, other):
        return self.age - other.age


if __name__ == '__main__':
    stu1 = Student('a', 18, 160)
    stu2 = Student('b', 19, 170)

    if stu1 > stu2:
        print('----')

    if stu1 < stu2:
        print('====')

结果:

====

四、内存管理

五、包的使用

封装:
对一个功能的封装 --- 函数
对多个功能的封装 --- 模块和类
对多个数据进行封装 --- 类、字典
对多个类进行封装 --- 模块
对多个模块进行封装 --- 包(包含一个init.py文件的文件夹)

上一篇 下一篇

猜你喜欢

热点阅读