Я хотел бы обновить поле в классе данных, но я знаю имя поля только во время выполнения, а не во время разработки.
#!/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]
но это заканчивается в «Ошибка типа: объект« Шаблон »не поддерживает назначение элемента»