nolimits
nolimits

Reputation: 83

More elegant way to iterate over classes in python?

I am learning python classes and want to have classes for like 1000 fruits (just example for many things) and thought I loop over an array A or so. I wrote this noobish code and does what I want from it, but I am not sure if there is a better/more elegant way you experts might see? Especially since the a.type and a.yo() is in the loop.

Edit: The exercise is to check fruits from Singapore on whether they fulfil the cheap criteria. The cheap criteria is defined by the Seaport. There will be many more criteria such as age, temperature, delays, condition - as properties of each fruit.

def buy(x = -1):
    print(f"buying {x}")

class FRUITS:
    def __init__(self, cheap= -1):
    self.cheap = cheap
    # many more later


A = ["APPLE", "BANANA"]
for a in A:

    class a(FRUITS):
        def __init__(self):
            super().__init__()
    
        def yo():

            print(a.cheap)
        
            if a.cheap == "yes":
                try:
                    buy(x)
                    print("Bought dat")
                except:
                    print("Buying didn't work")
            else:
                print("Buy conditions not met")


    a.cheap = 'yes' # from dataframe later
    a.yo()

Upvotes: 0

Views: 719

Answers (1)

Brett La Pierre
Brett La Pierre

Reputation: 533

import random

class Fruit:
    def __init__(self, id, name, cheap):
        self.id = id
        self.name = name
        self.cheap = cheap

def buy_cheap_fruit(fruit_collection):
    """Passes in a collection of fruit and returns a list of the cheap fruit"""
    cheap_fruit = []
    for fruit in fruit_collection:
        if fruit.cheap: # you could say if fruit.cheap == True: as well
            cheap_fruit.append(fruit)
    return cheap_fruit


# here there can only an apple or banana choice but we could add a bunch more names if we want
fruit_names = ["APPLE", "BANANA"]
fruits = []

# here we are creating objects derived from the Fruit class
# for index, _ in enumerate(range(1000), start=1):
#     name = random.choice(fruit_names)
#     fruit = Fruit(index, name)
#     fruits.append(fruit)

# The code above does the same thing and is cleaner but this is simpler for a newer programmer.
count = 0
for _ in range(1000):
    count += 1
    name = random.choice(fruit_names)
    cheap_status = random.choice([True, False])
    fruit = Fruit(count, name, cheap_status) # creating objects here
    fruits.append(fruit)

# here we are printing out the name that has been randomly selected and the id associated with it
# for fruit in fruits:
#     print(f'id: {fruit.id} name: {fruit.name}')

all_the_cheap_fruits = buy_cheap_fruit(fruits)

for fruit in all_the_cheap_fruits:
    print(f"The fruit {fruit.name} with an id of {fruit.id} is in the cheap fruit list because the status is {fruit.cheap}")

Upvotes: 1

Related Questions