• Python 【类的继承】


    一.类的继承

    #类的继承
    
    class Animal(object):  #Animal类继承object
    
        def __init__(self,color):
    
            self.color = color
    
        def eat(self):
    
            print("动物在吃!")
    
        def run(self):
    
            print("动物在跑")
    
    
    
    class Cat(Animal):  #Cat继承Aninal  继承[属性和方法]
    
        pass
    
    
    
    cat = Cat("白色")
    
    
    print(cat.color)
    
    cat.eat()
            

    上面定义Animal类,Animal类继承基类object,Animal类中有属性color和方法

    Cat类继承Animal类,继承了属性和方法

    二.super()继承

    #类的继承
    
    class Animal(object):  #Animal类继承object
    
        def __init__(self,color):
    
            self.color = color
    
        def eat(self):
    
            print("动物在吃!")
    
        def run(self):
    
            print("动物在跑")
    
    
    
    class Cat(Animal):  #Cat继承Aninal  继承[属性和方法]
    
        pass
    
    
    class Dog(Animal):  #继承时候,方法重名用子方法
    
        def __init__(self,name,age,color):
            super(Dog,self).__init__(color)  #super表示父类,调用父类的初始化方法
    
            self.name = name
    
            self.age = age
    
        def eat(self):  #方法重名
            print("狗仔!")
            
    
    
    
    dog = Dog("狗仔队",12,"黑色")

    现在根据上面的继承后,再次创建一个Dog类,定义了与Animal类重名的eat方法

    使用super(className,self).__init__(color),super表示的是父类,让className继承父类的color属性,不需要再次重写属性

    在实例化的过程中,传入参数,类的实例化传入的参数对象本身self就是一个参数

  • 相关阅读:
    Java Class的field如果以小写t开头
    ACM集训日志——day1——15.7.8
    分金币 Uva 11300
    RMQ小结
    Poj 水题
    Codeforces Round #278 (Div. 2)
    poj 3685
    poj 3579
    vConsole
    js更换自定义鼠标指针图片
  • 原文地址:https://www.cnblogs.com/Crown-V/p/12389320.html
Copyright © 2020-2023  润新知