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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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






































以上是关于Python自学之乐-继承的新式类与经典类的主要内容,如果未能解决你的问题,请参考以下文章

新式类与经典类的比较

python基础===新式类与经典类

python------面向对象介绍之经典类与新式类的继承顺序

python2中的新式类与经典类区别

python2中的新式类与经典类区别

python新式类与旧式类