我有一个基本服务,它为所有服务提供通用方法。此外,此BaseService用作服务注册表:

class BaseService:
    instances = {}

    @classmethod
    def get_instance(cls) -> 'BaseService':
        if cls.instances.get(cls) is None:
            cls.instances[cls] = cls()
        return cls.instances[cls]

class Service1(BaseService):
    pass

class Service2(BaseService):
    pass

Service1.get_instance()
Service2.get_instance()
Service1.get_instance()


get_instance()方法返回子类实例,我觉得当前的注释-> 'BaseService'不正确。如何正确注释此方法?

最佳答案

就像我在评论中说的那样,对基类的类方法进行此操作是
这是有问题的,因为根据定义,该方法将与所有子类共享。对于单身人士尤其如此。

解决方法是为每个子类赋予其自己的类似名称的方法,并带有适当的返回值注释。尽管可以使用类装饰器来完成此操作,如我的答案的早期版本中所示,但是使用元类似乎是一种更干净的方法,因此我相应地更新了我的答案:

class BaseServiceMeta(type):
    """ Metaclass that properly annotates the return value of the get_instance() method of
        any subclasses of the BaseService class.
    """
    def __new__(metaclass, classname, bases, classdict):
        cls = super(metaclass, metaclass).__new__(metaclass, classname, bases, classdict)
        if classname != 'BaseService':  # subclass?

            # define function with the correct return value annotation
            def get_instance() -> classname:
                return super(cls, cls).get_instance()  # call superclass classmethod

            setattr(cls, 'get_instance', get_instance)  # override inherited method

        return cls

class BaseService(metaclass=BaseServiceMeta):  # metaclass added
    instances = {}

    @classmethod
    def get_instance(cls) -> 'BaseService':
        if cls.instances.get(cls) is None:
            cls.instances[cls] = cls()
        return cls.instances[cls]

class Service1(BaseService):
    pass

class Service2(BaseService):
    pass

# show that the methods have the correct return annotation
print(repr(BaseService.get_instance.__annotations__['return']))  # -> 'BaseService'
print(repr(   Service1.get_instance.__annotations__['return']))  # -> 'Service1'
print(repr(   Service2.get_instance.__annotations__['return']))  # -> 'Service2'

# call subclass methods to show they return the correct singleton instance of each type
print(Service1.get_instance())  # -> <__main__.Service1 object at 0x004A07D0>
print(Service2.get_instance())  # -> <__main__.Service2 object at 0x004A07F0>
print(Service1.get_instance())  # -> <__main__.Service1 object at 0x004A07D0>

关于python - 通用单例的类型提示?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43023405/

10-12 17:31
查看更多