如何从字典键/值创建对象属性?

Ben*_*ndy 1 python dictionary python-3.x

我有一个excel文件,其中包含一些必需的参数及其值,我试图将它们提供给__init__我的类实体的函数.我知道下面必须设置self.key在每个值依次,但我应该"屏蔽"了(?) .key

class Customer:
    def __init__(self):
        for key, value in zip(excelDF.attribs, excelDF.values):
            if key!=None and value !=None:
                self.key= value
Run Code Online (Sandbox Code Playgroud)

举一个我正在尝试的例子:

excelDF.attribs=['name','telephone']
excelDF.values=['Tom','01234-567890']
customer1=Customer()
print(customer1.name)
print(customer1.telephone)
Run Code Online (Sandbox Code Playgroud)

给...

Tom
01234-567890
Run Code Online (Sandbox Code Playgroud)

Dee*_*ace 6

你应该使用setattr:

class Customer:
    def __init__(self):
        for key, value in zip(excelDF.attribs, excelDF.values):
            if key is not None and value is not None:
                setattr(self, key, value)
Run Code Online (Sandbox Code Playgroud)

如果密钥恰好是无效的Python标识符,则只能访问它getattr.

用法示例:

keys = ['a', 'b', 'c']
values = [1, 2, 3]

class Customer:
    def __init__(self):
        for key, value in zip(keys, values):
            if key is not None and value is not None:
                setattr(self, key, value)

cust = Customer()
print(cust.a, cust.b, cust.c)
# 1 2 3
Run Code Online (Sandbox Code Playgroud)