Home > database >  check if an attribute of a class is assigned to a instance
check if an attribute of a class is assigned to a instance

Time:10-09

i'm making a little game for fun and i ran into an issue, how can i see if the email of a member is assigned to a instance?

file1:

if "[email protected]" in file2:
   print("ok"
else:
   print("not ok")

file2:

player1 = Player("testName1", "[email protected]", "testpwd1"
player2 = Player("testName2", "[email protected]", "testpwd2"
player3 = Player("testName3", "[email protected]", "testpwd3"
player4 = Player("testName4", "[email protected]", "testpwd4"

CodePudding user response:

overriding the __contains__ method will do the trick.

So:

def __contains__(self, key):
        return key in self.email

Edit:

If for some reason you don't care which attribute contains the value, this will work:

def __contains__(self, key):
    return key in list(self.__dict__.values())

CodePudding user response:

If you put Players in a list then you could use a dictionary to index that list. This example lets you look up by name and email at the same time.

file2.py

class Player:

    def __init__(self, name, email, pwd):
        self.name = name.lower()
        self.email = email.lower()
        self.pwd = pwd
        
players = [
    Player("testName1", "[email protected]", "testpwd1"),
    Player("testName2", "[email protected]", "testpwd2"),
    Player("testName3", "[email protected]", "testpwd3"),
    Player("testName4", "[email protected]", "testpwd4")
]

# index to lookup up player by name or email

player_index = {player.name:player for player in players}
player_index.update({player.email:player for player in players})

file1.py

import file2

if file2.player_index.get("[email protected]".lower(), None) is not None:
    print("ok")
else:
    print("not ok")

It would be common to place that players list in some other data structure like a CSV file or even a pickled file. Assuming you want to update players dynamically, it becomes awkward to represent them as class instances in a .py file. But that's an enhancement for another time.

  • Related