如何从字典创建对象,其中键是名称对象,值是属性?使用循环
How to create objects from a dict where the keys are the name objects and the values are the attributes? Using a loop
class Cars(object):
def __init__(self,brand=None,color=None,cost=None):
self.brand = brand
self.color = color
self.cost = cost
假设我有 300 辆汽车(从 car1 到 car300)
dict = {"car1":["Toyota","Red",10000],
"car2":["Tesla","White",20000],
"car3":["Honda","Red",15000]
}
我尝试过的:
dict1 = globals()
for k,v in dict.items():
dict1[f"{k}"] = Cars(v[0],v[1],v[2])
print(k,v)
这是最好的方法吗?
这是一种激进的方式吗?
我想学习一种高效、安全的方法
对所有汽车使用字典,而不是全局汽车。
您可以通过字典理解一步创建它。
all_cars = {name: Coche(brand, color, cost) for name, (brand, color, cost) in dict.items()}
print(all_cars['car1'].brand)
关闭。首先,您似乎有一个名字问题,Cars
与 Coche
。而且你不应该使用 dict
作为变量名。您确实需要考虑将这些变量放在全局命名空间中是否是个好主意。除此之外,您不应使用不向引用的变量添加任何内容的 F 字符串。您可以使用 *v
解压缩列表,并使用字典理解而不是循环
my_dict = {k:Cars(*v) for k,v in dict.items()}
class Cars(object):
def __init__(self,brand=None,color=None,cost=None):
self.brand = brand
self.color = color
self.cost = cost
假设我有 300 辆汽车(从 car1 到 car300)
dict = {"car1":["Toyota","Red",10000],
"car2":["Tesla","White",20000],
"car3":["Honda","Red",15000]
}
我尝试过的:
dict1 = globals()
for k,v in dict.items():
dict1[f"{k}"] = Cars(v[0],v[1],v[2])
print(k,v)
这是最好的方法吗?
这是一种激进的方式吗?
我想学习一种高效、安全的方法
对所有汽车使用字典,而不是全局汽车。
您可以通过字典理解一步创建它。
all_cars = {name: Coche(brand, color, cost) for name, (brand, color, cost) in dict.items()}
print(all_cars['car1'].brand)
关闭。首先,您似乎有一个名字问题,Cars
与 Coche
。而且你不应该使用 dict
作为变量名。您确实需要考虑将这些变量放在全局命名空间中是否是个好主意。除此之外,您不应使用不向引用的变量添加任何内容的 F 字符串。您可以使用 *v
解压缩列表,并使用字典理解而不是循环
my_dict = {k:Cars(*v) for k,v in dict.items()}