小编Joh*_*ohn的帖子

将类的自身命名为变量名

是否可以在 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,但至少能够这样引用它们。

python class

2
推荐指数
1
解决办法
874
查看次数

标签 统计

class ×1

python ×1