zoukankan      html  css  js  c++  java
  • 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.
  • 相关阅读:
    linux下shell显示-bash-4.1#不显示路径解决方法
    update chnroute
    An error "Host key verification failed" when you connect to other computer by OSX SSH
    使用dig查询dns解析
    DNS被污染后
    TunnelBroker for EdgeRouter 后记
    mdadm详细使用手册
    关于尼康黄的原因
    Panda3d code in github
    Python实例浅谈之三Python与C/C++相互调用
  • 原文地址:https://www.cnblogs.com/huskiesir/p/10447136.html
Copyright © 2011-2022 走看看