• Python自学之乐-继承的新式类与经典类


    #Author:clark
    class Animal(object):#python3中新式类写法,继承object(所有类的基类)
    #kind = "" #类属性
    def __init__(self,name,age,food):#name等是实例属性 init方法叫做构造方法__del__是析构方法
    self.Name = name
    self.Age = age
    self.food = food
    def eat(self):
    print("%s is eat %s" %(self.Name,self.food))
    def barking(self):
    print("%s is barking"%self.Name)

    class dog(Animal): #狗是动物的子类,如果增加新的属性并且要继承父类的属性,按照下面这样去写
    def __init__(self,name,age,food,kind):
    #Animal.__init__(self,name,age,food) 经典类的写法,这种写法比较繁琐,如果该类继承多个类的相同属性,就需要每个类都要写,新式类使用super写法,写一个就行
    super(dog,self).__init__(name,age,food)
    self.kind = kind
    def barking(self):
    print("the barking of %s is wangwangwang!"%self.Name)
    class cat(Animal):
    def __init__(self,name,age,food,kind):
    #Animal.__init__(self,name,age,food)
    super(cat,self).__init__(name,age,food)
    self.kind = kind
    def barking(self):
    print("the barking of %s is miaomiaomiao"%self.Name)

    dog_teddy = dog("ahuang",3,"bone","teddy")
    dog_teddy.eat()
    cat_xiaohua = cat("xiaohua",2,"fish","cat")
    cat_xiaohua.eat()
    dog_teddy.barking()
    cat_xiaohua.barking()

    运行结果为:

    ahuang is eat bone
    xiaohua is eat fish
    the barking of ahuang is wangwangwang!
    the barking of xiaohua is miaomiaomiao

  • 相关阅读:
    Qt QLineEdit、QCombox、QCompleter 实现模糊搜索
    Windows CMD命令大全
    Excel后缀.xls和.xlsx有什么区别
    Qt 3D入门(二)
    Qt 3D入门(一)
    用C语言给NI公司数据采集卡编程序进行电压数据采集
    用C语言给NI数据采集卡编程序实现多路数据的同时采集
    Qt 蓝牙库基础
    Qt 类库模块划分详解
    Qt Modbus通信(RTU模式)
  • 原文地址:https://www.cnblogs.com/clarkxhb/p/7536065.html
Copyright © 2020-2023  润新知