当我动态设置类的属性时:
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不能遵循。
有没有办法让 MyPy 理解?
Django 已经实现了:
from django.db import models
class Person(models.Model):
age = models.IntegerField()
person = Person()
print(type(Person.age)) # <class 'django.db.models.query_utils.DeferredAttribute'>
print(type(person.age)) # <class 'int'>
person.age = 25 # No error
Django 是如何做到这一点的?
UYOU
catspeake
相关分类