[英]How to use a class attribute as the type hint for a method inside the class?
class Foo:
method_type: type
def method(self) -> ???:
# code
# Example use:
class FooStr(Foo):
method_type = str
foo_str = FooStr().method() # should be str according to vscode's intellisense
class FooInt(Foo):
method_type = int
foo_int = FooInt().method() # similarly, this should be int
请注意,只需替换???
就我测试过的而言, with method_type
不起作用。
我将如何 go 这样做?
class 属性是一个运行时值,而 Python 并不真正支持依赖于值的类型。 Python 也没有类型成员。 所以总而言之,不,这是不可能的。 你需要使用通用的
T = TypeVar("T")
class Foo(Generic[T]):
def method(self) -> T:
...
class FooStr(Foo[str]):
...
class FooInt(Foo[int]):
...
这是相似的,如果不完全相同的话。
如果您想了解更多有关差异的信息,请在Scala中对此进行讨论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.