• python3 继承与组合


    什么叫继承?

      所谓继承,就是class_A里面的功能从class_B中直接获取,从而节约了代码且使用方便。

    什么叫组合?

      除了继承,还有一种我们可以实现目的的方式,那就是组合,同样可以节约代码。只不过,class_A与class_B的关系不再是父类与子类的关系,变成了A中有B。

    继承大致分为3种类型:

      1.隐式继承

      2.显式覆盖

      3.显式修改

      接下来我会通过写代码举例子的方式去更好的让读者们去理解:

    # 隐式继承
    
    class Persion(object):
    
        def sleep(self):
            print("I need to sleep.")
    
        def eat(self):
            print("I need to eat.")
    
    class Student(Persion):
        
        pass
    
    
    b = Student()
    
    b.sleep()
    
    b.eat()
    
    # 这种在子类中没有对父类的内容进行修改的,称为隐式继承
    # 输出内容为下:
    I need to sleep.
    I need to eat.
    # 显示覆盖
    
    class Persion(object):
    
        def sleep(self):
            print("I need to sleep.")
    
        def eat(self):
            print("I need to eat.")
    
    class Student(Persion):
    
        def sleep(self):
            print("Student need to sleeping 8 hours")
    
    b = Student()
    
    b.sleep()
    
    b.eat()
    
    # 像这种在子类中拥有着和父类一样的方法或属性,并且修改了其方法的内容的,称为显式覆盖。
    # 输出内容为下:
    Student need to sleeping 8 hours
    I need to eat.
    # 显式修改
    
    class Persion(object):
    
        def sleep(self):
            print("I need to sleep.")
    
        def eat(self):
            print("I need to eat.")
    
    class Student(Persion):
    
        def sleep(self):
            print("Student need to sleeping 8 hours")
            super(Student, self).sleep()
            print("after")
    
    a = Persion()
    
    b = Student()
    
    b.sleep()
    
    b.eat()
    
    # 像这种在子类中对父类的方法或属性修行修改(增加自己的东西),这样的继承称为显式修改
    # 输出内容为下:
    Student need to sleeping 8 hours
    I need to sleep.
    after
    I need to eat.

    组合的例子:

    # 组合与继承达到的效果是一致的,只不过组合没有隐式这么一说。假如说class_A中有方法AA,而如果class_B也想拥有方法AA,则必须要创建这个方法AA才会具有。
    # 其实,组合实际上就是在class_B上实例化了一个对象,在此基础上去调用这个对象的函数。
    class Persion(object): def sleep(self): print("I need to sleep.") def eat(self): print("I need to eat.") class Student(object): def __init__(self): # 在生成实例前进行初始化操作的方法 self.other = Persion() # 定义一个对象并实例化 def sleep(self): self.other.sleep() # 通过对象去调用sleep函数 print("But student need to sleeping 8 hours") def eat(self): print("student like to eat apple.") self.other.eat() # 通过对象去调用eat函数 a = Persion() b = Student() b.sleep() b.eat() # 输出内容为下: I need to sleep. But student need to sleeping 8 hours student like to eat apple. I need to eat.
  • 相关阅读:
    java环境变量配置 win7/win8 java配置
    (JSON转换)String与JSONObject、JSONArray、JAVA对象和List 的相互转换
    (yum)更新yum报错:yum makecache: error: argument timer: invalid choice: 'fast' (choose from 'timer')
    (ElasticSearch)中文字符串精确搜索 term 搜不到结果
    (端口)打开阿里云服务组端口和防火墙端口
    (乱码)Spring Boot配置文件出现乱码解决方案
    (特殊字符)url中包含特殊字符导致请求报错的解决方案
    (端口占用)Windows 查看所有端口和PID
    (注释)IDEA快捷键注释不能自动对齐
    (JDK)oracle下载jdk需要注册?
  • 原文地址:https://www.cnblogs.com/huskiesir/p/10447136.html
Copyright © 2020-2023  润新知