首页 > 解决方案 > Python - 如何在使用泛型类型时访问其他类方法?

问题描述

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

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

标签: pythongenericspycharmtype-hinting

解决方案


推荐阅读