2

如何使它在@dataclass-decorated Python 类中设置拼写错误的字段时引发异常?

我想要一种实用的方法来做到这一点。我需要编写自己的装饰器吗?

@dataclass
class C(object):
    x: int = 1

obj = C()
obj.y = 2  # should raise an exception
4

3 回答 3

6

一种直接的方法(适用于任何类)是定义__slots__

In [1]: from dataclasses import dataclass

In [2]: @dataclass
   ...: class Foo:
   ...:     __slots__ = 'bar','baz'
   ...:     bar: int
   ...:     baz: int
   ...:

In [3]: foo = Foo(42, 88)

In [4]: foo.biz = 10
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-d52b60444257> in <module>()
----> 1 foo.biz = 10

AttributeError: 'Foo' object has no attribute 'biz'

插槽的目的是作为一个小的优化。它允许类的实例使用符号表而不是 adict作为类的命名空间。它略微提高了属性访问的速度,并且可以显着提高每个实例的内存使用率(因为实例没有在dict底层实现),但是它不允许动态属性设置。

这实际上是我最喜欢__slots__.

请注意,在对插槽使用继承时必须小心,至少,如果您希望子类保留插槽行为。

于 2018-12-14T05:02:24.437 回答
1

一种方法是将数据类标记为frozen

>>> from dataclasses import dataclass
>>> @dataclass(frozen=True)
... class C:
...     x: int = 1
...     
>>> c = C()
>>> c.y = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<string>", line 3, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'y'

但请注意,这会使所有现有属性(例如x在本例中)也是只读的。

于 2019-11-21T07:14:28.490 回答
0

您可以提供自己的__setattr__()方法,只允许分配给已知字段。

例子:

@dataclass
class C:
    x: int = 1

    def __setattr__(self, k, v): 
        if k not in self.__annotations__: 
            raise AttributeError(f'{self.__class__.__name__} dataclass has no field {k}')
        super().__setattr__(k, v)

然后失败/工作如下:

[ins] In [3]: obj = C() 
         ...: obj.y = 2                                                                                                                                                                       
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-7a568eb098b1> in <module>
      1 obj = C()
----> 2 obj.y = 2

<ipython-input-2-d30972f86fbb> in __setattr__(self, k, v)
      5     def __setattr__(self, k, v):
      6         if k not in self.__annotations__:
----> 7             raise AttributeError(f'{self.__class__.__name__} dataclass has no field {k}')
      8         super().__setattr__(k, v)
      9 

AttributeError: C dataclass has no field y

[ins] In [4]: obj.x = 23                                                                                                                                                                      

[ins] In [5]: obj.x                                                                                                                                                                           
Out[5]: 23
于 2021-03-06T16:35:11.723 回答