使用列表列表创建对象



我想保留一个温度探头列表,这些探头将定期读取温度读数。我想将创建温度探头对象的每个实例所需的参数存储在列表列表中。然后,我想从此列表列表创建每个实例,并使用每个嵌套列表的索引 0 命名每个对象。

例如,我希望使用相应的参数创建实例 Probe1、Probe2 和 Probe3。然后,我想从列表中的每个探头中获取温度读数。

我希望能够添加无限的探针,而无需更改代码。

我遇到的问题是,当我尝试使用 Probe1、Probe2 或 Probe3 python 做任何事情时,它会告诉我它们不存在。我是编程新手,我确定我错过了一些明显的东西。

class max31865(object):
def __init__(self, name, R_REF, csPin):
self.name = name
self.R_REF = R_REF
self.csPin = csPin
def readTemp(self):
#code here to check temp

probe_list=[["Probe1", 430, 8],["Probe2", 430, 9],["Probe3", 430, 10]]
for probe in probe_list:
x = str(probe[0])
x = max31865(*probe)
for probe in probe_list:
readTemp(probe[0])

我不确定你到底想要什么,但根据您的问题,这里有两个可能的用例:

您需要一个简单的探测对象列表,该列表由初始化参数列表生成:

最直接的方法是使用可迭代解包运算符(*(与列表理解相结合:

probe_list = [["Probe1", 430, 8],["Probe2", 430, 9],["Probe3", 430, 10]]
probe_obj_list = [max31865(*probe) for probe in probe_list]

现在,您可以对列表中的每个对象调用readTemp(),如下所示:

probe_obj_list[1].readTemp() # Read the temperature of the second object

或者循环执行:

for probe in probe_obj_list:
probe.readTemp()

您希望能够按名称查找探测对象:

考虑使用字典(也称为地图(。

probe_list = [["Probe1", 430, 8],["Probe2", 430, 9],["Probe3", 430, 10]]
probe_obj_map = {probe[0] : max31865(*probe) for probe in probe_list} # Dict comprehension

现在,您可以按名称访问探测对象,如下所示:

probe_obj_map["Probe1"].readTemp() # Accessing the object mapped to by the string "Probe1"

如果您需要遍历probe_list并按名称查找对象,您可以(尽管我不确定为什么您需要这样做(:

for probe_args in probe_list:
probe_obj_map[probe_args[0]].readTemp() # Access the object mapped to by the first argument of the nested list (i.e. the name)

代码更正:

class Max31865(object):
def __init__(self, name, R_REF, csPin): # missing `:` here
self.name = name
self.R_REF = R_REF
self.csPin = csPin
def read_temp(self):
# code here to check temp
# print the object's attributes or do anything you want
print('Printing in the method: ', self.name, self.R_REF, self.csPin)

probe_list=[["Probe1", 430, 8],["Probe2", 430, 9],["Probe3", 430, 10]]
for probe in probe_list:
# x = str(probe[0]) # probe[0] already is str
x = Max31865(*probe) # Here x is instantiated as `Max31865` object
print('Printing in the loop: ', x.name, x.R_REF, x.csPin)
x.read_temp() # Then call the `read_temp()` method.
# for probe in probe_list:
#     readTemp(probe[0])
# This loop is confusing, just as @RafaelC noted in comment,
# 1. `readTemp` is a *method* of `Max31865` object, not a function you can call directly.
# 2. `readTemp` has no argument in it's definition, and you are giving one.

最新更新