我有一个包含一些必需参数及其值的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
举一个我正在尝试的例子:
excelDF.attribs=['name','telephone']
excelDF.values=['Tom','01234-567890']
customer1=Customer()
print(customer1.name)
print(customer1.telephone)
...给出
Tom
01234-567890
答案 0 :(得分:5)
您应该使用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)
如果密钥碰巧是无效的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
答案 1 :(得分:1)
使用type定义类的另一种不太传统的方法:
Customer = type("Customer",
(),
dict(zip(excelDF.attribs, excelDF.values)))
答案 2 :(得分:0)
我想提出两种选择:
#!/usr/bin/env python3
class Customer:
def __init__(self, **kwargs):
self.name = kwargs.get("name")
self.number = kwargs.get("number")
class Customer2:
name = ""
number = ""
@classmethod
def from_dict(cls, d):
o = cls()
for k in [k for k in vars(cls) if not k.startswith("_")]:
setattr(o, k, d.get(k))
return o
keys = ["name", "number", "bla"]
values = ["John", "00109563221", "Blub"]
data = {k: v for k, v in zip(keys, values)}
c1 = Customer(**data)
c2 = Customer2.from_dict(data)
print(c1.name)
print(c2.number)
这里的重点在于构造函数拉动所需的数据,而不是采取所有相关的内容。
洞穴:解决方案2依赖于这样一个事实,即您只需要哑数据对象,其中您感兴趣的唯一字段是已定义的类变量。