Bring object 'out of' Class?

Arnaud Delobelle arnodel at googlemail.com
Sun Jun 1 03:18:23 EDT 2008


dave <squareswallower at 1ya2hoo3.net> writes:

> Hello,
>
> I'm currently on the class section of my self-taught journey and have
> a question about classes:  is it possible to bring a object created
> inside the class definitions outside the class so it can be accessed
> in the interpreter?
>
> For example, right now I'm working (within Allen Downey's Python
> Programmer book) with creating a 'hand' of cards.  I want to be able
> to deal to 'x' amount of cards to 'x' amount of hands and then be able
> to manipulate those hands afterwards.  I'm not sure if even what I'm
> asking is possible or if I'm getting ahead of myself.
>
> As always, thanks for all your help.  My learning is greatly enhanced
> with everyone's input on this board.  Please feel free to
> comment/critique the code...
>
> Here is the section of code that deals hands (but doesn't do anything
> past that):
>
>    def deal_cards(self, num_of_hands, num):
>        '''deals x amount of cards(num) to each hand'''
>        for i in range(num_of_hands):
>            handname = Hand('hand%d' % i)
>            self.deal(handname, num)
>            print '::::%s::::' % (handname.label), '\n', handname, '\n'
>

You need to use a 'return' statement:

   def deal_cards(self, num_of_hands, num):
       '''deals x amount of cards(num) to each hand'''
       hands = []
       for i in range(num_of_hands):
           newhand = Hand('hand%d' % i)
           self.deal(newhand, num)
           hands.append(newhand)
           print '::::%s::::' % (handname.label), '\n', handname, '\n'
       return Hand


Then you can write:

>>> hands = deck.deal_cards(4, 5) # On fait une belotte?

And I don't see the need of defining 'Hand' inside 'Deck'.

HTH

-- 
Arnaud



More information about the Python-list mailing list