zoukankan      html  css  js  c++  java
  • 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就是一个参数

  • 相关阅读:
    Linux-05安装python3,jupyter(朱皮特)
    Linux-04Vim
    calloc()的使用
    根目录挂载位置错误记录
    arm裸机通过uboot运行hello world程序测试结果
    编译Uboot——错误记录
    将make的输出重定向到文件(转)
    Linux下JDK+Eclipse安装
    使用gdb+core查看错误信息
    Ubuntu下安装tftp
  • 原文地址:https://www.cnblogs.com/Crown-V/p/12389320.html
Copyright © 2011-2022 走看看