gpt4 book ai didi

python - @property 装饰器类型提示

转载 作者:行者123 更新时间:2023-12-02 18:19:50 31 4
gpt4 key购买 nike

我能以某种方式告诉 mypy 我的 getter (salary) 的类型吗?

from typing import Any
class MyProperty:
def __init__(self, getter) -> None:
self.getter = getter

def __get__(self, obj, objtype=None) -> Any:
return self.getter(obj)

class Person:
def __init__(self) -> None:
self.x = 7400.5

@MyProperty
def salary(self) -> float:
return self.x

def check(something: str) -> None:
# should issue: ... incompatible type float; expected str
pass

p = Person()
check(p.salary) # <----- Success: no issues found in 1 source file

请注意,这不如 this related post 雄心勃勃.

最佳答案

您可以使用泛型并相应地注释您的函数。因此,您基本上定义了一个 TypeVar 并注释了应该被修饰以返回该类型的函数以及返回该类型的 get 函数。

from typing import Any, Callable, TypeVar, Generic
T = TypeVar("T")

class MyProperty(Generic[T]):
def __init__(self, getter: Callable[[Any], T]) -> None:
self.getter = getter

def __get__(self, obj, objtype=None) -> T:
return self.getter(obj)

class Person:
def __init__(self) -> None:
self.x = 7400.5

@MyProperty
def salary(self) -> float:
return self.x

关于python - @property 装饰器类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71018821/

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