简体   繁体   English

"如何将类属性设置为类方法返回类型?"

[英]How to set class property as class method return type?

I got a class A who has a class method and take it's class property as return type.我有一个 A 类,它有一个类方法并将它的类属性作为返回类型。

And a got a class B who inherit from class A. A 有一个继承自 A 类的 B 类。

How to set get_instance<\/code> return type in A and to inform B get the right type?如何在 A 中设置get_instance<\/code>返回类型并通知 B 获取正确的类型?

# typings.py
from typing import TypeVar, Type

AType = TypeVar("AType", bound="A")

T = TypeVar("T", int, str)


class A:
    TYPE = int

    @classmethod
    def get_instance(cls: Type[AType]) -> "AType.TYPE":
        return cls.TYPE()


class B(A):
    TYPE = str


a = B.get_instance()

reveal_type(a)

Parameterise<\/em> over the TYPE<\/code> by making the class Generic<\/code> .通过使类Generic<\/code>对TYPE<\/code>进行参数化<\/em>。 This allows to refer to the class attribute TYPE<\/code> and the return type with the same type variable:这允许使用相同类型变量引用类属性TYPE<\/code>和返回类型:

from typing import TypeVar, Type, Generic

T = TypeVar("T", str, int)


class Base(Generic[T]):
    TYPE: Type[T]

    @classmethod
    def get_instance(cls: "Type[Base[T]]") -> "T":
        return cls.TYPE()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何设置 class 方法从 class 属性返回动态输入 - How to set a class method return typing dynamically from a class property Python类具有方法“ set”,如何引用内置set类型? - Python class has method “set”, how to reference builtin set type? 如何使类通用并正确推断其方法的返回类型 - How to make a class generic and correctly infer the return type of its method Class 方法覆盖任何类型的属性 - Class method override with any type of property 无法将属性类型设置为自定义 class 列表 - Unable to set type of property to list of custom class 如何从类中返回一个方法? - How to return a method from a class? 使用装饰器在python中的类方法上设置类的属性 - Set the property of a class using decorators on a class method in python Python,selenium webdriver - 我需要基类方法来返回其子类的类型。 如何实现? - Python, selenium webdriver - I need base class method to return type of its child class. How to achieve it? 基于 Python 中的 class 变量的 class 方法中的返回类型 - Return type in a class method based on a class variable in Python 将自定义类设置为该类中方法的可选参数类型 - Set a custom class as an optional argument's type to a method within that class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM