• 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

  • 相关阅读:
    一步一步写平衡二叉树(AVL树)
    sql关键字
    Remoting技术的应用
    算法:最大公约数
    算法冒泡排序
    C#编码好习惯
    利用VB.Net编程实现PC与掌上电脑PPC间的双向通信
    .Net Remoting与Server 对象详解
    算法迭代和递归
    SQL关键字系列之:minus与intersect
  • 原文地址:https://www.cnblogs.com/clarkxhb/p/7536065.html
Copyright © 2020-2023  润新知