Python重写父类的三种方法

1.基础应用

class Aniaml(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))
posted @   阿无oxo  阅读(66)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示