Python-如何在使用泛型类型时访问其他类方法?

Python-如何在使用泛型类型时访问其他类方法?,python,generics,pycharm,type-hinting,Python,Generics,Pycharm,Type Hinting,我想要一个classmethod返回正确的类型,所以我为它声明泛型类型。 class的任何子类也将满足类型提示。 但是在from_int()中,cls将无法访问Pycharm中的other()方法。 正确的方法是什么 from typing import Type, TypeVar T = TypeVar('T', bound='TrivialClass') class TrivialClass: # ... @classmethod def from_int(cl

我想要一个classmethod返回正确的类型,所以我为它声明泛型类型。
class
的任何子类也将满足类型提示。 但是在
from_int()
中,
cls
将无法访问Pycharm中的
other()
方法。 正确的方法是什么

from typing import Type, TypeVar

T = TypeVar('T', bound='TrivialClass')

class TrivialClass:
    # ...

    @classmethod
    def from_int(cls: Type[T], int_arg: int) -> T:
        # no suggestion for other, since cls type is Type[T]
        cls.other()
        return cls(...)

    @classmethod
    def other(cls):
        pass

为什么您首先要注释
cls
mypy
和PyCharm接受它而不使用类型注释,因为
mypy
和PyCharm知道
classmethod
的第一个参数的类型。不过,您必须先修复
other()
方法。@Wombatz我不使用mypy,只使用pycharm。声明
Type[T]
以使其返回正确的子类类型(如果我不这样做的话)
from_int
将返回任何类型@Wombatz
其他用途是工厂方法,如复制和反序列化。对于类方法,您还可以使用类型[T]:
@Wombatz定义泛型cls,因为当您对该类进行子类化时,希望
subclass.from_int()
被识别为子类类型,而不是父类。