我想保留一份温度探测器的清单,这些探测器将定期读取温度读数。我想将创建温度探测器对象的每个实例所需的参数存储在一个列表列表中。然后我想从列表列表中创建每个实例,并使用每个嵌套列表的索引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])
代码更正:
我不确定您到底想要什么,但基于您的问题,这里有两个可能的用例:
您需要一个简单的探测对象列表,该列表由初始化参数列表生成:
最直接的方法是将iterable解包操作符(
*
)与list comprehension结合使用:现在可以对列表中的每个对象调用
readTemp()
,如下所示:或者循环进行:
您希望能够按名称查找探测对象:
考虑使用dictionary(也称为map)。你知道吗
现在可以按名称访问探测对象,如下所示:
如果需要循环
probe_list
并按名称查找对象,则可以(尽管我不确定为什么需要这样做):相关问题 更多 >
编程相关推荐