简体   繁体   English

在 Python 中迭代类的实例

[英]Iterate Over Instances of a Class in Python

I've created a class called Equipment, to which I can pass attributes describing the piece of equipment, the sensor type monitoring it, and the data pin that sensor is associated with, for a given instantiation.我创建了一个名为 Equipment 的类,我可以向它传递描述设备的属性、监控它的传感器类型以及传感器关联的数据引脚,用于给定的实例。 I then initialize four (arbitrary number) different instances of that class, pass them the attributes that are relevant, and create a list of the variables that represent those instances.然后我初始化该类的四个(任意数量)不同的实例,向它们传递相关的属性,并创建一个代表这些实例的变量列表。 From there, I defined a function, based on a for loop, whose job it is to iterate over those instances so that I can pull data from their associated sensors recursively using the contents of the given instance.从那里,我定义了一个基于 for 循环的函数,它的工作是迭代这些实例,以便我可以使用给定实例的内容递归地从它们关联的传感器中提取数据。 However, when I go to implement this, I receive a TypeError saying that the Equipment object is not iterable.然而,当我去实现这个时,我收到一个 TypeError 说 Equipment 对象是不可迭代的。

To me, this does not make much sense, since I've created instances of the class, which, presumably should exist in memory somewhere and be referenceable using their variable name.对我来说,这没有多大意义,因为我已经创建了类的实例,它大概应该存在于内存中的某个地方并且可以使用它们的变量名进行引用。 Thus, I'm really asking Python to iterate over a list object that contains references to instances of a given class, which shouldn't require the class itself to be iterable.因此,我真的要求 Python 迭代包含对给定类的实例的引用的列表对象,这不应该要求类本身是可迭代的。 Rather, from my understanding, this should allow for a specific instance to be referenced, and its attributes retrieved.相反,根据我的理解,这应该允许引用特定实例并检索其属性。

What am I missing in my current understanding, and how can I start to approach the implementation that I have described/am aiming for?我目前的理解中缺少什么,我如何开始接近我所描述/目标的实现?

Here are the relevant code snippets:以下是相关的代码片段:

class Equipment:

    def __init__(self, equipmentType, sensor, pin):
        self.equipmentType = equipmentType
        self.sensor = sensor
        self.pin = pin       

dht11Sensor = Adafruit_DHT.DHT11

minus20 = Equipment("Minus 20 Freezer", dht11Sensor, 4)
minus80 = Equipment("Minus 80 Freezer", dht11Sensor, 4)
incubator24 = Equipment("24 Degree Incubator", dht11Sensor, 4)
incubator18 = Equipment("18 Degree Incubator", dht11Sensor, 4)

equipment = [minus20, minus80, incubator24, incubator18]

def recursiveCheck(equipmentList):

    for equipment in equipmentList:
        humidity, temperature = Adafruit_DHT.read(equipment.sensor, equipment.pin)

        if humidity is not None and temperature is not None:
            print(f"Your {equipment.equipmentType} is currently {temperature} degrees C and the humidity is {humidity}%")

        else:
            recursiveCheck(equipment)

    time.sleep(5)
    recursiveCheck(equipmentList)

recursiveCheck(equipment)

your problem is that you are calling the method recursively and hence in the second round you call it with the object itself instead of the list!您的问题是您正在递归调用该方法,因此在第二轮中您使用对象本身而不是列表来调用它!

in the for-loop this line:在 for 循环这一行中:

recursiveCheck(equipment)

you are calling the function with one Equipment object and when it runs, it tries to do the for-loop on this object which is not your list!您正在使用一个 Equipment 对象调用该函数,当它运行时,它会尝试在这个不是您列表的对象上执行 for 循环! you probably wanted your code to be like this:你可能希望你的代码是这样的:

class Equipment:

    def __init__(self, equipmentType, sensor, pin):
        self.equipmentType = equipmentType
        self.sensor = sensor
        self.pin = pin       

dht11Sensor = Adafruit_DHT.DHT11

minus20 = Equipment("Minus 20 Freezer", dht11Sensor, 4)
minus80 = Equipment("Minus 80 Freezer", dht11Sensor, 4)
incubator24 = Equipment("24 Degree Incubator", dht11Sensor, 4)
incubator18 = Equipment("18 Degree Incubator", dht11Sensor, 4)

equipment = [minus20, minus80, incubator24, incubator18]

def recursiveCheck(equipmentList):

    for equipment in equipmentList:
        humidity, temperature = Adafruit_DHT.read(equipment.sensor, equipment.pin)

        if humidity is not None and temperature is not None:
            print(f"Your {equipment.equipmentType} is currently {temperature} degrees C and the humidity is {humidity}%")

        else:
            recursiveCheck(equipmentList)

    time.sleep(5)
    recursiveCheck(equipmentList)

recursiveCheck(equipment)

so to recap, the first time that your code runs, it runs ok and doesn't encounter any error (you could fact-check it with a simple print or a counter), the failure happens when your code goes to else statement in the for-loop because you are trying to pass an object instead of a list!所以回顾一下,您的代码第一次运行时,它运行正常并且没有遇到任何错误(您可以使用简单的打印或计数器对其进行事实检查),当您的代码转到 else 语句时会发生故障for 循环,因为您试图传递一个对象而不是一个列表!

=== update: === 更新:

so if you want to start the list from a given index when it fails you could do this:因此,如果您想在失败时从给定索引开始列表,您可以这样做:

class Equipment:

    def __init__(self, equipmentType, sensor, pin):
        self.equipmentType = equipmentType
        self.sensor = sensor
        self.pin = pin       

dht11Sensor = Adafruit_DHT.DHT11

minus20 = Equipment("Minus 20 Freezer", dht11Sensor, 4)
minus80 = Equipment("Minus 80 Freezer", dht11Sensor, 4)
incubator24 = Equipment("24 Degree Incubator", dht11Sensor, 4)
incubator18 = Equipment("18 Degree Incubator", dht11Sensor, 4)

equipment = [minus20, minus80, incubator24, incubator18]

def recursiveCheck(equipmentList, index=0):

    for i in in range(index, len(equipmentList)):
        equipment = equipmentList[i]
        humidity, temperature = Adafruit_DHT.read(equipment.sensor, equipment.pin)

        if humidity is not None and temperature is not None:
            print(f"Your {equipment.equipmentType} is currently {temperature} degrees C and the humidity is {humidity}%")

        else:
            recursiveCheck(equipmentList, i)
            return;

while True:
    recursiveCheck(equipment)
    time.sleep(5)

so I have made your function non-recursive because if I didn't do that it would have became a mess in runtime, and it might have gotten hard to follow where it is going!!所以我让你的函数是非递归的,因为如果我不这样做,它会在运行时变得一团糟,而且可能很难跟踪它的去向!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM