Thursday, May 6, 2010

Python – Learning Classes

A simple program I made while learning about classes

Code:

class Market:
    '''Manages a list of items I need to buy'''

    items = 0
    basket = []

    def __init__(self, item):
        '''Writes down the item'''

        self.item = item

    def Item(self):
        '''I decide I want to buy the item'''
        print('I have to buy', self.item)
        Market.items += 1

    def ItemBought(self):
        '''I bought the item'''

        print('I have bought', self.item)

        Market.items += -1
        Market.basket.append(self.item)

        print('Items left to buy :', Market.items)
        print('The basket contains', Market.basket[:])

    def Check():
        '''Checks if I have bought everything so I can go home'''

        if Market.items == 0:
            print('I have everything. Time to go home!')
        else:
            print('I have more shopping to do!')

    Check = staticmethod(Check)

item_a = Market('bananas')
item_a.Item()
item_b = Market('apples')
item_b.Item()
item_b.ItemBought()
Market.Check()
item_a.ItemBought()
Market.Check()


Output:

I have to buy bananas
I have to buy apples
I have bought apples
Items left to buy : 1
The basket contains ['apples']
I have more shopping to do!
I have bought bananas
Items left to buy : 0
The basket contains ['apples', 'bananas']
I have everything. Time to go home!

I made a version with better output before but I am too lazy to upload it now. I will do it tomorrow :-)

No comments:

Post a Comment