gpt4 book ai didi

python - 使用仅在运行时已知的字段名称更新数据类中的字段

转载 作者:行者123 更新时间:2023-12-01 08:59:35 25 4
gpt4 key购买 nike

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

#!/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:'Template'对象不支持项目分配”

最佳答案

您可以尝试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 仅包含作为数据类字段的键,那么这应该可以完成工作。

关于python - 使用仅在运行时已知的字段名称更新数据类中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52556605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com