簡體   English   中英

使用列表創建對象

[英]Using a list of lists to create objects

我想保留一個將定期獲取溫度讀數的溫度探測器列表。 我想將創建溫度探測器對象的每個實例所需的參數存儲在列表中。 然后,我想從該列表列表中創建每個實例,並使用每個嵌套列表的索引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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM