0

在不对类进行更改的情况下,实现一个描述符,该描述符检查获取到实例属性的值是否具有正确的类型。

我找到了一个相关的帖子,但我不知道如何在我的情况下实现它。 了解 __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
4

1 回答 1

1

以下可能符合您的要求。

class ArticleField:

    def __init__(self, field_type: typing.Type[typing.Any]):
        self.field_type = field_type
        self.value = None
    
    def __get__(self, instance, owner=None):
        return self.value
    
    def __set__(self, instance, value):
        if isinstance(value, self.field_type):
            self.value = value
        else:
            raise TypeError(f'Invalid type {type(value)}')
于 2020-07-06T05:22:36.800 回答