遍历数据类并填充值
Looping over a dataclass and fill values
我想用值填充数据类(不是在初始化时)。我试过了:
from random import randint
from dataclasses import dataclass
@dataclass
class VData:
var_a: list = None
var_b: list = None
var_c: list = None
X = VData
for var in VData.__dataclass_fields__:
l = [randint(0, 10), randint(0,10)]
X.__setattr__(X, var, l)
但出现错误:can't apply this __setattr__ to type object
。如何正确循环变量?
使用 asdict
和 setattr
而不是它们的等价物。
from random import randint
from dataclasses import dataclass, asdict
@dataclass
class VData:
var_a: list = None
var_b: list = None
var_c: list = None
# you were missing a () which instantiates the object
inst = VData()
# Here, asdict gives you the dictionary form of a dataclass instance
# fields would work too as @rv.ketch pointed out
# if you don't have a need for the values of the dict
for var in asdict(inst):
l = [randint(0, 10), randint(0,10)]
setattr(inst, var, l)
print(inst)
使用fields
。作为一般规则,避免像 __setattr__
这样的魔术方法。
from random import randint
from dataclasses import dataclass, fields
@dataclass
class VData:
var_a: list = None
var_b: list = None
var_c: list = None
X = VData()
xfilds = fields(VData)
for var in xfilds:
l = [randint(0, 10), randint(0,10)]
setattr(X, var.name, l)
# VData(var_a=[10, 2], var_b=[8, 9], var_c=[0, 6])
注意:xfilds
被缓存,asdict
没有。
我想用值填充数据类(不是在初始化时)。我试过了:
from random import randint
from dataclasses import dataclass
@dataclass
class VData:
var_a: list = None
var_b: list = None
var_c: list = None
X = VData
for var in VData.__dataclass_fields__:
l = [randint(0, 10), randint(0,10)]
X.__setattr__(X, var, l)
但出现错误:can't apply this __setattr__ to type object
。如何正确循环变量?
使用 asdict
和 setattr
而不是它们的等价物。
from random import randint
from dataclasses import dataclass, asdict
@dataclass
class VData:
var_a: list = None
var_b: list = None
var_c: list = None
# you were missing a () which instantiates the object
inst = VData()
# Here, asdict gives you the dictionary form of a dataclass instance
# fields would work too as @rv.ketch pointed out
# if you don't have a need for the values of the dict
for var in asdict(inst):
l = [randint(0, 10), randint(0,10)]
setattr(inst, var, l)
print(inst)
使用fields
。作为一般规则,避免像 __setattr__
这样的魔术方法。
from random import randint
from dataclasses import dataclass, fields
@dataclass
class VData:
var_a: list = None
var_b: list = None
var_c: list = None
X = VData()
xfilds = fields(VData)
for var in xfilds:
l = [randint(0, 10), randint(0,10)]
setattr(X, var.name, l)
# VData(var_a=[10, 2], var_b=[8, 9], var_c=[0, 6])
注意:xfilds
被缓存,asdict
没有。