python - class类 (五) 继承补充-子类继承父类属性/函数方法
子类继承父类属性/函数方法:
#方式一:(原生方式,不建议使用) class Dongwu(object): def __init__(self,name,sex,old): self.name = name self.sex = sex self.old = old def eat(self): print("吃~~~~~~`") class Cat(Dongwu): def __init__(self,name,sex,old,num): Dongwu.__init__(self,name,sex,old) self.num = num def eat(self): Dongwu.eat(self) return "疯狂的吃......" wc = Cat("wc",'女',4,'普通') print(wc.eat()) #这种方式一旦父类修改,子类的跟父类相关的所有属性都得修改!!!
# 方式二:(通过surper()方式继承父类的属性以及函数方法) class Dongwu(object): def __init__(self,name,sex,old): self.name = name self.sex = sex self.old = old def eat(self): print("吃~~~~~~`") class Cat(Dongwu): def __init__(self,name,sex,old,num): #不需要写父类名,也不要写self super().__init__(name,sex,old) self.num = num def eat(self): super().eat() return "疯狂的吃!!!!" wc = Cat("wc",'女',4,'普通') print(wc.eat()) print(wc.__class__)
既要脚踏实地,也需仰望天空