class Animal:
#!!!!父类中定义init方法
def __init__(self,name):
self.name = name
print('对象的初始化')
self.color = '黄色'
def eat(self):
print('能吃的动物')
def run(self):
print('能跑的动物')
。
class Dog(Animal):
#!!init和父类的init名字一样,所以叫方法的重写
def __init__(self,name):
super().__init__(self) #!!!!当写了这行代码时候不覆盖init内容 dog.color output:黄色 不报错
self.name = name
print('狗的初始化')
def set_name(self):
print('狗的名字是%s'%self.name)
def eat(self):
print('狗的eat方法')
dog= Dog('小白') #如果子类中对某个方法重写了,优先调用 子类自己本身的方法
print(dog.name)
print(dog.color)#NameError: name 'color' is not defined 父类中color没有调用
#因为子类重写了init方法
#虽然init方法重写了,但是还想自动调用父类的init方法
#需要在子类内加入super().__init__() 即主动调用父类的init方法
print(dog.eat())#如果希望调用父类里的eat方法则需要在子类里加入super().eat()