zoukankan      html  css  js  c++  java
  • python__基础 : 类的继承,调用父类的属性和方法

    1.继承,调用父类属性方法

    在python里面,继承一个类只需要这样写:

    class Animal:
        def heshui(self):
            print('动物正在喝水')
    
    class Cat(Animal):
        pass

    这样Cat就有了Animal的所有属性和方法,调用的时候直接调用就可以了:

    #接上面代码
    
    cat = Cat()
    
    cat.heshui()
    
    
    >>>动物正在喝水

    这个时候,如果子类想重写父类的方法,可以直接重写:

    class Animal:
        def heshui(self):
            print('动物正在喝水')
    
    class Cat(Animal):
        def heshui(self):
            print('猫正在喝水')
    cat = Cat()
    cat.heshui()
    
    >>>猫正在喝水

    如果想调用父类的 heshui 这个方法,可以用 super() :

    class Animal:
        def heshui(self):
            print('动物正在喝水')
    
    class Cat(Animal):
        def heshui(self):
            super().heshui()
    cat = Cat()
    cat.heshui()
    
    >>>动物正在喝水

    2.强制调用父类私有属性方法

        如果父类的方法是私有方法,如 def __heshui(self)  这样的话再去调用就提示没有这个方法,其实编译器是把这个方法的名字改成了 _Animal__heshui(),如果强制调用,可以这样:

    class Animal:
        def __heshui(self):
            print('动物正在喝水')
    
    class Cat(Animal):
        def heshui(self):
            super()._Animal__heshui()
    
    cat = Cat()
    cat.heshui()
    
    >>>动物正在喝水

    最后,如果自己也定义了 __init__ 方法,那么父类的属性是不能直接调用的:

    class Animal:
        def __init__(self):
            self.a = 'aaa'
    
    class Cat(Animal):
        def __init__(self):
            pass
    
    cat = Cat()
    print(cat.a)
    
    
    >>>AttributeError: 'Cat' object has no attribute 'a'

    那么可以在 子类的 __init__中调用一下父类的 __init__ 方法,这样就可以调用了:

    class Animal:
        def __init__(self):
            self.a = 'aaa'
    
    class Cat(Animal):
        def __init__(self):
            super().__init__()  #也可以用 Animal.__init__(self)  这里面的self一定要加上
    
    cat = Cat()
    print(cat.a)
    
    >>>aaa
  • 相关阅读:
    二级指针内存模型(二)
    Winserver-FailoverCluster验证异常
    IIS-This configuration section cannot be used at this path.
    SQL SERVER-Extendevent捕获堵塞
    SQL SERVER-Extendevent
    Powershell-加域脚本
    SQL SERVER-端口Port
    WinServer-SMTP服务
    Linux-开机启动程序
    SQL SERVER-修改服务器名称
  • 原文地址:https://www.cnblogs.com/cccy0/p/9040192.html
Copyright © 2011-2022 走看看