Python中重写父类方法的几种实现方式
作者:吹吹风会发光
时间:2023-04-30
浏览:4
1.基础应用classAnimal(object):defeat(self):print("动物吃东西")classCat(Animal):defeat(self):print("猫吃鱼")#格式一:父类名.方法名(对象)Animal.eat(self)#格式二:super(本类名,对象).方法名()super(Cat,self).eat()#格式三:super()方法名()super().eat()cat1=Cat()cat1.eat()print(cat1)2.实际应用#用元类实现单例模式classS
本文目录
1.基础应用
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)2.实际应用
#用元类实现单例模式
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))3.注意
1.当一个类存在多继承时,它继承的多个父类有相同的父类A,在重写其父类时需要注意
方法一:父类名.方法名(对象)
父类A会被调用多次(根据继承的个数)
重写父类时根据需要传递所需要的参数
方法二:super(本类名,对象).方法名()
父类A也只会被调用一次
重写父类方法必须传递所有参数
2.当一个类存在继承,且已经在子类中重写相应的变量,改变父类的变量不会对子类有影响
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)
输出结果
1 1 1
1 2 1
3 2 3
作者最新文章
Agent Space智能体如何进行功能测试
2026-11-01 08:45
Proxifier怎么卸载:Windows标准版彻底移除与配置清理指南
2026-10-30 09:37
七彩虹 iGame RTX 5070 Ti Ultra SFF 显卡图赏:嘻哈涂鸦风,设计更潮酷
2026-10-26 16:48
viso如何导入word的详细操作步骤教程
2026-10-20 16:03
蛙蛙写作苹果手机更新新版本怎么下载
2026-10-15 19:40
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































