0

I'm trying to create an application using python that lets the Admin of the app delete an user by matching his name in the list

Here is the code :

    class Personne:
        def __init__(self, prenom, nom):
            self.prenom = prenom
            self.nom = nom

        def __str__(self):
            return "{0} {1} {2}".format(self.prenom, self.nom)


    class SuperUser(Personne):
        def __init__(self, nom, prenom, droit, arg=0):
            Personne.__init__(self, prenom, nom)
            self.droit = droit
            self.arg = arg

        def __str__(self):
            return "{0} {1} is {2}".format(self.prenom, self.nom, self.droit)



    Utilisateur1 = SuperUser("Chris", "Cat", "Admin", "John")
    Utilisateur2 = SuperUser("John", "Doe", "Membre")
    Utilisateur3 = SuperUser("Karma", "Frost", "Membre")
    Utilisateur4 = SuperUser("Emma", "Stone", "Staff")

    list = [Utilisateur1, Utilisateur2, Utilisateur3, Utilisateur4]

    for utilisateur in list:
        print "From list:" + str(utilisateur)

        if utilisateur.droit == "Admin":
            print utilisateur.arg

            #utilisateur.nom takes my name which is Chris and should take the name of John Doe which is Utilisateur2
            if utilisateur.arg == utilisateur.nom: 
                print utilisateur.nom #the part for deleting an user would be creater later.

How can I make it so that in the last 2 lines, utilisateur.arg takes the name as Utilisateur2 from the list?

Horai Nuri
  • 5,358
  • 16
  • 75
  • 127
  • Sidenote: Having `arg` as either 0 or a string with the name of a user is a little strange API-wise IMHO. The conventional value for ”no value” is `None` in Python. – BlackJack Aug 12 '15 at 16:35

1 Answers1

2

If I understood your question correctly, you would like to find matches of utilisateur.arg in the list. Your condition is that the list's item.nom == utilisateur.arg.

This code should do the trick:

utilisateur2 = next((u for u in list if u.nom == utilisateur.arg), None)
if utilisateur2 == None:
   # not found

References:

Community
  • 1
  • 1
ypnos
  • 50,202
  • 14
  • 95
  • 141
  • The solution works fine thanks! I have a question with this method, how do you render the name only ? I tried `print utilisateur2.nom` but gives me an Attribute error. – Horai Nuri Aug 12 '15 at 15:48
  • @Sia That can't be because then the comparison in the generator expression already would have raised that `AttributeError`. – BlackJack Aug 12 '15 at 16:23