当我动态设置类的属性时:
from typing import TypeVar, Generic, Optional, ClassVar, Any
class IntField:
type = int
class PersonBase(type):
def __new__(cls):
for attr, value in cls.__dict__.items():
if not isinstance(value, IntField):
continue
setattr(cls, attr, value.type())
return cls
class Person(PersonBase):
age = IntField()
person = Person()
print(type(Person.age)) # <class 'int'>
print(type(person.age)) # <class 'int'>
person.age = 25 # Incompatible types in assignment (expression has type "int", variable has type "IntField")
age
属性的类型将是int
类型,但MyPy不能跟在后面。在
有没有办法让我明白?在
Django已实施:
^{pr2}$Django是怎么做到的?在
由于您在类上定义了字段,实际的方法是键入hint字段。注意,您必须告诉
mypy
不要检查行本身。在这是最小的改变,但相当僵硬。在
通过使用带有伪签名的helper函数,可以创建自动键入的通用提示:
^{pr2}$这就是
attrib
库提供其遗留提示的方式。这种风格允许隐藏注释的所有魔力/技巧。在因为元类可以检查注释,所以不需要在字段中存储类型。您可以使用空的
Field
作为元数据,并为类型使用注释:这就是
attrib
提供其python3.6+属性的方式。它既通用又符合注释样式。请注意,这也可以用于常规基类而不是元类。在帕特里克·豪是对的,我试图用错误的方式解决这个问题。描述词是正确的方法:
MyPy
完全可以理解这一点。谢谢!在相关问题 更多 >
编程相关推荐