【发布时间】:2021-11-04 11:18:18
【问题描述】:
是否可以在 python 中迭代数据类实例的属性?比如我想在__post_init__加倍整数属性:
from dataclasses import dataclass, fields
@dataclass
class Foo:
a: int
b: int
def __post_init__(self):
self.double_attributes()
def double_attributes(self):
for field in fields(Foo):
field = field*2
x = {
'a': 1,
'b': 2
}
y = Foo(**x)
>>> TypeError: unsupported operand type(s) for *: 'Field' and 'int'
如何访问类实例的值并将其设置为类似下面但在循环中的其他值?
@dataclass
class Foo:
a: int
b: int
def __post_init__(self):
self.double_a()
self.double_b()
def double_a(self):
self.a = self.a*2
def double_b(self):
self.b = self.b*2
【问题讨论】:
标签: python class attributes iteration python-dataclasses