gpt4 book ai didi

python - 类方法返回实例的类型注解

转载 作者:太空狗 更新时间:2023-10-29 21:21:47 24 4
gpt4 key购买 nike

我应该如何注释返回 cls 实例的 @classmethod?这是一个不好的例子:

class Foo(object):
def __init__(self, bar: str):
self.bar = bar

@classmethod
def with_stuff_appended(cls, bar: str) -> ???:
return cls(bar + "stuff")

这会返回一个 Foo,但更准确地说,会返回调用它的 Foo 的子类,因此使用 -> "Foo" 进行注释不会足够好。

最佳答案

诀窍是显式地向cls 参数添加注释,结合TypeVar,对于generics。 , 和 Type, 到 represent a class rather than the instance itself ,像这样:

from typing import TypeVar, Type

# Create a generic variable that can be 'Parent', or any subclass.
T = TypeVar('T', bound='Parent')

class Parent:
def __init__(self, bar: str) -> None:
self.bar = bar

@classmethod
def with_stuff_appended(cls: Type[T], bar: str) -> T:
# We annotate 'cls' with a typevar so that we can
# type our return type more precisely
return cls(bar + "stuff")

class Child(Parent):
# If you're going to redefine __init__, make sure it
# has a signature that's compatible with the Parent's __init__,
# since mypy currently doesn't check for that.

def child_only(self) -> int:
return 3

# Mypy correctly infers that p is of type 'Parent',
# and c is of type 'Child'.
p = Parent.with_stuff_appended("10")
c = Child.with_stuff_appended("20")

# We can verify this ourself by using the special 'reveal_type'
# function. Be sure to delete these lines before running your
# code -- this function is something only mypy understands
# (it's meant to help with debugging your types).
reveal_type(p) # Revealed type is 'test.Parent*'
reveal_type(c) # Revealed type is 'test.Child*'

# So, these all typecheck
print(p.bar)
print(c.bar)
print(c.child_only())

通常,您可以不注释cls(和self),但是如果您需要引用特定的子类,您可以添加一个explicit annotation。 .请注意,此功能仍处于试验阶段,在某些情况下可能存在错误。您可能还需要使用从 Github 克隆的最新版本的 mypy,而不是 pypi 上可用的版本——我不记得该版本是否支持类方法的此功能。

关于python - 类方法返回实例的类型注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44640479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com