子类继承自父类之后,如果子类没有写构造函数,默认用父类的构造函数,传入父类的参数
class Animal: def __init__(self, name, color): self.name=name self.color=color def eat(self): print('吃') def drink(self): print('喝') def run(self): print('跑') def sleep(self): print('睡') class Dog(Animal): def bark(self): print('%s 在叫'% (self.name)) dog=Dog("小花","grey") dog.bark()
如果子类自己有构造函数,默认用子类构造函数
class Animal: def __init__(self, name, color): self.name=name self.color=color def eat(self): print('吃') def drink(self): print('喝') def run(self): print('跑') def sleep(self): print('睡') class Dog(Animal): def __init__(self, name): self.name=name def bark(self): print('%s 在叫'% (self.name)) dog=Dog("小花") dog.bark()