将类的自身命名为变量名

Joh*_*ohn 2 python class

是否可以在 self 上使用输入的名称,例如 yaml/dict 键,而实际上不知道该键?

意思是,如果有一些数据,例如:

entries = [
    {'foo': 'foo 1', 'bar': 'bar 1'},
    {'foo': 'foo 2', 'bar': 'bar 2'},
]
Run Code Online (Sandbox Code Playgroud)

我们如何在不显式预编程“foo”和“bar”来命名 self 变量的情况下执行以下操作?

class entry(object):
    def __init__(self):
        self.foo = entries[0]['foo']
        self.bar = entries[0]['bar']
Run Code Online (Sandbox Code Playgroud)

我想这些自我分配不必命名为 foo 和 bar,但至少能够这样引用它们。

Iai*_*ton 5

您可以使用内置函数setattr在 Python 中添加/设置对象的属性

def __init__(self):
    for k, v in entries[0].items():
        setattr(self, k, v)
Run Code Online (Sandbox Code Playgroud)