检查lis中类/对象的属性

2024-09-29 19:20:25 发布

您现在位置:Python中文网/ 问答频道 /正文

import nxppy
import time

class student: # Object giving first and last name, idCard and statut
    def __init__(self, name, idCard, present):
        self.name = name
        self.idCard = idCard
        self.present = None

class_TS4 = []
class_TS4.append(student('moureton etienne', '4DC3A150', None))
class_TS4.append(student('metzinger axel', '5FG998H2', None))
# print(class_1S4)

# Instantiate reader
mifare = nxppy.Mifare()

while True:
    try:
        uid = mifare.select()
        for student in class_TS4:
            # comparing uid to the each of the student's idCard attribute
            if uid == student.idCard:
                 student.present = True
                 print(student.present)
                 print(student.name)
                 break  # since uids are unique there is no point to check other students

    # Permet le polling
    except nxppy.SelectError:
        pass

        time.sleep(1)

你好,世界!我需要你尽快的帮助。。。我在Hihg学校做一个项目,我被阻止了。我从Python开始,在pi3b+运行的Raspbian上编程。你知道吗

我必须读取一些NFC卡的UID,这没有问题。但我必须检查我读取的UID是否与匹配自我识别卡“我的一个班级。如果是,我想更改“自我表现“将包含UID的对象设置为True。你知道吗

至少,我的目标是增加30个像这样的“学生”,程序可以告诉我哪一个通过了他的卡。你知道吗

idCard的UID对于每个学生都是唯一的和恒定的。你知道吗

谢谢大家<;3


Tags: nameimportselfnonetrueuidtimestudent
1条回答
网友
1楼 · 发布于 2024-09-29 19:20:25

当前将read uid与类的实例进行比较,该实例将始终是False。你应该把苹果和苹果进行比较:

while True:
    uid = mifare.select()
    for student in class_TS4:
        # comparing uid to each of the student's idCard attribute
        if uid == student.idCard:
             student.present = True
             break  # since uids are unique there is no point to check other students

另一种更有效的方法是使用字典。这样uid查找将是O(1)

uids_to_student = {student.idCard: student for student in class_TS4}

while True:
    # Read UID data
    uid = mifare.select()
    try:
        uids_to_student[uid].present = True
    except KeyError:
        print('No student with this UID exist in class')

顺便说一句,student.__init__接受present参数,但不处理它。从签名中删除、使用或为其指定默认值:

class student:
    def __init__(self, name, idCard, present=None):
        self.name = name
        self.idCard = idCard
        self.present = present

相关问题 更多 >

    热门问题