继承
class Animal():
def eat(self):
print("Animal")
class Dog(Animal):
# Override 覆盖了父类的eat方法
def eat(self): #如果不用super之类的方法的话,Dog.eat的输出结果就是Dog eat,而不是Animal
print("Dog eat")
class Pig(Animal):
def __init__(self):
print("执行了父类的构造方法")
def eat(self):
print("Pig eat")
class Fish(Animal):
def __init__(self, color):
print("执行了父类Fish的构造方法")
self.color = color
class GoldFish(Fish):
def __init__(self, color):
super().__init__(color) #调用父类的方法用super()
print("执行子类的构造方法")
class Monster(Fish, Dog, Pig): #C3算法,父类都有同一方法,继承最前面父类的方法,没有方法的话向后找,第一个有方法的父类
def __init__(self, color):
Fish.__init__(self, color)
Pig.__init__(self)
def eat(self):
print("-------------------")
Dog.eat(self) #作用和super一样,用“父类”“.”“方法”调用父类的方法
Pig.eat(self)
print("-------------------")
print(Monster.mro()) #输出c3算法的过程(广度优先,先看父类,然后父类的父类。。。。)
dog = Dog()
dog.eat()
m = Monster("color") #实例化对象的同时,调用父类的构造方法
m.eat() #输出本类中的eat方法,然后通过 父类.eat(self) 调用父类的eat方法
g = GoldFish('Gold')
ps:python中没有重载和重写,只能是覆盖,如果没有用super()等方法的话,就只运行本类中的方法而不运行父类的方法
本文重点“c3算法”,”super()“,还有等同于super的”父类.方法“
以上内容仅供参考,切勿用于商业用途,如有雷同,纯属偶然!