1、
class Animal(): def __init__(self,type,voice): self.type = type self.voice = voice def animal_type(self): print('这种动物是,{0}'.format(self.type)) def animal_voice(self): print('{0}的声音是{1}!'.format(self.type, self.voice)) class Dog(Animal): #类的继承,默认继承object。子类默认继承父类的属性和方法;继承多个父类,如果有重名的函数,先写哪个,继承哪个; # 如果多个父类初始化函数参数不一致,当调用涉及不一样参数的属性、方法时,会报错;可以重写子类的init方法 def animal_voice(self): #当子类与父类重名时,是重写该方法
super(Dog,self).animal_voice() #超继承,继承的父类。改写父类的方法,同时还要使用这段代码;super这个关键字,会通过子类Dog,找到父类的方法animal_voice print('函数的重写') def dog_foot(self): #子类自己的函数 print('{0}有四肢'.format(self.type)) animal = Animal('狗','汪汪汪') animal.animal_type() animal.animal_voice() dog = Dog('二哈','wangwangwang') dog.animal_type() dog.animal_voice() dog.dog_foot() 控制台输出: 这种动物是,狗 狗的声音是汪汪汪! 这种动物是,二哈 函数的重写
二哈的声音是wangwangwang! 二哈有四肢
2、