Saturday, April 7, 2012

Python: How to search a list of class element by their data (self.name) variable

Reference: http://stackoverflow.com/q/10052322/1276534
Credits: nitin, kindall

Imagine you have a class of Food, and you want to create a list that store your class of Food. How do you search your class element within your list? Take a look at the code.
class Food:
    def __init__(self, name):
        self.name = name

chicken = Food('Egg')
cow = Food('Beef')
potato = Food('French Fries')

# And then you create the list of food?
myFoodList = [chicken, cow, potato]
The way you want to implement your class so you can search through them by their name variable is done via dictionary. (This is one way to do it, set also might work depend on your class's implementation and required functionality).
class Food:
    lookup = {}
    def __init__(self, name):
        self.name = name
        Food.lookup[name] = self

chicken = Food('Egg')
cow = Food('Beef')
potato = Food('French Fries')

# Example of a lookup from the dictionary
# If your name is in your class Food's lookup dictionary
if 'Egg' in Food.lookup:
    # Do something that you want
    print (Food.lookup['Egg'].name)

No comments:

Post a Comment