Python 3.7 数据类:给未定义的属性赋值时引发错误
Python 3.7 dataclass: Raise error when assigning a value to undefined attribute
我想将数据类的使用限制为代码的用户,并且想知道如何在以下上下文中引发错误:
from dataclasses import dataclass
@dataclass
class Foo:
attr1: str
foo = Foo("1")
foo.attr2 = "3" #I want this line to raise an exception
目前最后一行成功,不改变底层对象。我希望最后一行抛出错误。
您可以像添加任何其他 class 一样将 __slots__
属性添加到数据 class。尝试创建实例的新属性将失败并显示 AttributeError
:
@dataclass
class Foo:
__slots__ = ("attr1",)
attr1: str
foo = Foo("1")
foo.attr2 = "3"
# AttributeError: 'Foo' object has no attribute 'attr2'
我想将数据类的使用限制为代码的用户,并且想知道如何在以下上下文中引发错误:
from dataclasses import dataclass
@dataclass
class Foo:
attr1: str
foo = Foo("1")
foo.attr2 = "3" #I want this line to raise an exception
目前最后一行成功,不改变底层对象。我希望最后一行抛出错误。
您可以像添加任何其他 class 一样将 __slots__
属性添加到数据 class。尝试创建实例的新属性将失败并显示 AttributeError
:
@dataclass
class Foo:
__slots__ = ("attr1",)
attr1: str
foo = Foo("1")
foo.attr2 = "3"
# AttributeError: 'Foo' object has no attribute 'attr2'