Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:指定用于继承的类方法的返回类型_Python_Inheritance_Typing_Class Method - Fatal编程技术网

Python:指定用于继承的类方法的返回类型

Python:指定用于继承的类方法的返回类型,python,inheritance,typing,class-method,Python,Inheritance,Typing,Class Method,我一直在试图理解如何在Python中指定类方法的返回类型,以便即使对于子类也能正确地解释它(例如,在我的Sphinx文档中) 假设我有: class Parent: @classmethod def a_class_method(cls) -> 'Parent': return cls() class Child(Parent): pass 如果希望父对象的返回类型为Parent,而子对象的返回类型为Child,则应指定什么作为a_class

我一直在试图理解如何在Python中指定类方法的返回类型,以便即使对于子类也能正确地解释它(例如,在我的Sphinx文档中)

假设我有:

class Parent:

    @classmethod
    def a_class_method(cls) -> 'Parent':
        return cls()


class Child(Parent):
    pass
如果希望父对象的返回类型为
Parent
,而子对象的返回类型为
Child
,则应指定什么作为
a_class_方法的返回类型?我也尝试过
\uuuuqalname\uuuuu
,但这似乎也不起作用。我应该不注释返回类型吗

提前谢谢

,通过使用类型变量注释
cls
。引用PEP 484中的一个示例:

T = TypeVar('T', bound='C')
class C:
    @classmethod
    def factory(cls: Type[T]) -> T:
        # make a new instance of cls

class D(C): ...
d = D.factory()  # type here should be D
,通过使用类型变量注释
cls
。引用PEP 484中的一个示例:

T = TypeVar('T', bound='C')
class C:
    @classmethod
    def factory(cls: Type[T]) -> T:
        # make a new instance of cls

class D(C): ...
d = D.factory()  # type here should be D

那很有帮助,谢谢。在Sphinx文档中,它将返回类型写为“T”,而不是相应子类的类型,但我想如果我认为T代表“与类相同的类型”,那也没关系。你知道把TypeVar称为“T”是否是一种常见的做法吗?如果是这样的话,当同一个模块中有多个类,您希望使用这些类时,标准做法是什么?这很有帮助,谢谢。在Sphinx文档中,它将返回类型写为“T”,而不是相应子类的类型,但我想如果我认为T代表“与类相同的类型”,那也没关系。你知道把TypeVar称为“T”是否是一种常见的做法吗?如果是这样的话,当在同一个模块中有多个类时,您希望使用这些类,那么标准的做法是什么?