Friday, May 7, 2010

Python – Classes Again

Here is the program with better output

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 {0}!'.format(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)
        if len(Market.basket) >= 2:
            print('The basket now contains', end=' ')
            for i in Market.basket[0:-1]:
                print(i, end=" ")
                print('and', Market.basket[-1])
        else:
            print('The basket now contains', end=' ')
            print(Market.basket[0])

    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 now contains apples
I have more shopping to do!
I have bought bananas
Items left to buy : 0
The basket now contains apples and bananas
I have everything. Time to go home!

No comments:

Post a Comment