在不对类进行更改的情况下,实现一个描述符,该描述符检查获取到实例属性的值是否具有正确的类型。
我找到了一个相关的帖子,但我不知道如何在我的情况下实现它。 了解 __get__ 和 __set__ 以及 Python 描述符
...
class ArticleField:
def __init__(self, field_type: typing.Type[typing.Any]):
pass
class Article:
def __init__(self, title: str, author: str, publication_date: datetime.datetime, content: str):
self.title = title
self.author = author
self.publication_date = publication_date
self.content = content
...
像这样:
>>> class Article:
... age = ArticleField(field_type=int)
>>> article = Article(...)
>>> article.age = "some string"
Traceback (most recent call last):
...
TypeError: expected an instance of type 'int' for attribute 'age', got 'str' instead