4

我想更新数据类中的字段,但我只在运行时知道字段名称,而不是在开发期间。

#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-

from dataclasses import dataclass # I use the backport to 3.6

@dataclass
class Template:
    number: int = 0
    name: str = "^NAME^"


oneInstance = Template()
print(oneInstance) # Template(number=0, name='^NAME^')
# If I know the variable name during development, I can do this:
oneInstance.number=77
# I get this from a file during runtime:
para = {'name': 'Jones'}
mykey = 'name'
# Therefore, I used exec:
ExpToEval = "oneInstance." + mykey + ' = "' + para[mykey] + '"'
print (ExpToEval) # oneInstance.name = "Jones"
exec(ExpToEval)  # How can I do this in a more pythonic (and secure) way?
print(oneInstance) # Template(number=77, name='Jones')

我需要类似的东西

oneInstance[mykey] = para[mykey]

但这最终导致“TypeError:'模板'对象不支持项目分配”

4

2 回答 2

4

您可以尝试replace()方法,如下所示:

from dataclasses import dataclass, replace

@dataclass
class Template:
    number: int = 0
    name: str = "^NAME^"

oneInstance = Template()
print(oneInstance)
para = {'name': 'Jones'}
oneInstance = replace(oneInstance, **para)
print(oneInstance)

para如果您的 dict仅包含作为数据类字段的键,那应该可以完成工作。

于 2018-10-28T07:53:33.417 回答
3

您可以使用setattr在运行时更新对象的属性:

oneInstance = Template()
setattr(oneInstance, 'name', 'Jones')  # this doesn't raise a TypeError
print(oneInstance.name)  # prints: 'Jones'
于 2019-03-11T13:45:53.617 回答