Python继承单例类后重写方法未生效问题如何解决
问题根因
你的单例实现里硬编码了父类SingletonParent的类名,导致无论哪个子类调用get_instance(),都会永远实例化父类对象、读取父类存储的单例实例,自然不会调用到子类的重写方法,具体问题点:
get_instance()用了静态方法,无法感知调用方的类类型,全程硬编码操作SingletonParent的_instance属性、硬编码实例化SingletonParent对象__init__方法同样硬编码操作SingletonParent的_instance属性,子类实例化时也会修改父类的单例存储
修复方案
将静态方法改为类方法,用cls参数替代所有硬编码的SingletonParent类名,同时每个子类单独维护自己的单例实例:
class SuperParent(): _instance = None class SingletonParent(SuperParent): # 改为类方法,cls代表当前调用方法的类 @classmethod def get_instance(cls): if cls._instance is None: # 实例化当前调用类的对象,而非固定父类 cls() return cls._instance def __init__(self): # 操作当前类的_instance,而非固定父类的 if self.__class__._instance is not None: raise RuntimeError('Use get_instance()') self.__class__._instance = self def print_hi(self): print("Hi from SingletonParent") class SingletonChild(SingletonParent): # 子类单独声明自己的_instance变量,避免和父类共用 _instance = None def print_hi(self): print("Hi from SingletonChild")
调用原有测试代码:
singleton_child = SingletonChild.get_instance() singleton_child.print_hi()
输出结果为Hi from SingletonChild,符合预期。
内容的提问来源于stack exchange,提问作者MikA
相关产品推荐
相关产品推荐

