【发布时间】:2019-09-28 23:22:33
【问题描述】:
有没有办法摆脱警告:
未解析的引用'DeviceManager' ...
对于这种单例模式?
class DeviceManager:
""" Holds all devices and manages their distributed use. """
instance: Union[DeviceManager, None] = None # warning Unresolved reference 'DeviceManager'
@staticmethod
def get_instance() -> DeviceManager: # warning Unresolved reference 'DeviceManager'
""" Singleton instance. """
if DeviceManager.instance is None:
DeviceManager()
return cast(DeviceManager, DeviceManager.instance)
def __init__(self) -> None:
""" Create instance. """
if DeviceManager.instance is None:
DeviceManager.instance = self
else:
raise Exception("This class is a singleton!")
截图:
【问题讨论】:
-
你可能想看看Creating a singleton in Python 了解更多创建单例的pythonic方法
-
好的,可能有更好的方法来编写单例,但上面链接提供的示例不使用类型提示。据我所知,它们都会遇到返回类型未解析或它们的类型是任何或对象的相同问题,这不是解决方案。 get_instance 返回类的类型很重要。
标签: python python-3.x pycharm