Etienne Moureton
Etienne Moureton

Reputation: 69

CHECK an attribut of a class/object in a list

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)

Hello world !I need your help as quik as possible... I work on a project at Hihg School and i'm blocked. I begin in Python and am programming on a Pi3 B+ running Raspbian.

I have to read the UID of some NFC card and this is working without problems. But I have to check if the UID i read match with the "self.idCard" one of my class. If yes, i want to change the "self.present" of the object containing the UID to True.

At least, the goal is that i add 30 "students" like those one and that the program can tell me which one passed his card.

The idCard's UID is unique and constant for each student.

Thanks all <3

Upvotes: 0

Views: 62

Answers (1)

DeepSpace
DeepSpace

Reputation: 81654

You currently compare the read uid to an instance of your class, which will always be False. You should compare apples to apples:

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

Another, more efficient approach would be to use a dictionary. This way uid lookup will be 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')

BTW, student.__init__ accepts a present argument but does not do anything with it. Either remove it from the signature, use it or give it a default value:

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

Upvotes: 2

Related Questions