#Author:clarkclass 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
时间: 2024-10-29 13:52:09