class Animal(object): def eat(self): print("动物吃东西") class Cat(Animal): def eat(self): print("猫吃鱼") # 格式一:父类名.方法名(对象) Animal.eat(self) # 格式二:super(本类名,对象).方法名() super(Cat, self).eat() # 格式三:super()方法名() super().eat() cat1 = Cat() cat1.eat() print(cat1)
#用元类实现单例模式 class SingletonType(type): instance = {} def __call__(cls, *args, **kwargs): if cls not in cls.instance: # 方式一: # cls.instance[cls] = type.__call__(cls, *args, **kwargs) # 方式二 # cls.instance[cls] = super(SingletonType, cls).__call__(*args, **kwargs) # 方式三 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))
Kaedah 1: Nama kelas induk (objek)
class Parent(object): x = 1 class Child1(Parent): pass class Child2(Parent): pass print(Parent.x, Child1.x, Child2.x) Child1.x = 2 print(Parent.x, Child1.x, Child2.x) Parent.x = 3 print(Parent.x, Child1.x, Child2.x)
Hasil keluaran
1 1 11 2 13 2 3
Atas ialah kandungan terperinci Apakah kaedah untuk menulis semula kelas induk dalam Python?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!