1.基础应用
class Aniaml(object)
def eat(self):
print("动物吃东西")
class Cat(Animal):
def eat(self):
print("猫吃鱼")
Animal.eat(self)
super(Cat,self).eat()
super().eat()
cat1=Cat()
cat1.eat()
print(cat1)
2.实际应用
class SingletonType(type):
instance = {}
def __call__(cls, *args, **kwargs):
if cls not in cls.instance:
cls.instance[cls] = super().__call__(*args, **kwargs)
return cls.instance[cls]
class Singleton(metaclass=SingletonType):
def __init__(self, name):
self.name = name
s1 = Singleton('1')
s2 = Singleton('2')
print(id(s1) == id(s2))