[Tutor] access class through indexing?

Jerry Hill malaclypse2 at gmail.com
Wed Aug 4 23:59:20 CEST 2010


On Wed, Aug 4, 2010 at 5:28 PM, Alex Hall <mehgcap at gmail.com> wrote:

> Here is my init, not half as pretty as yours, but it should work.
> Maybe this will explain the problem.
>
> def __init__(self, size, cards=None, fill=False):
>  #creates a pile of cards. If "fill"==true, it will auto-fill the
> pile starting from the Ace of Clubs up through the King of Spades,
> stopping if it exceeds the size arg.
>  #if the cards arg is not null, it will populate the pile with the
> cards in the list.
>  self=[]
>

This is the problem.  You cannot re-assign self inside the __init__ method
(or any method, for that matter).  Well, you can, but it doesn't do what you
expect.  All you're doing is shadowing the self that gets passed in to the
function, not changing it.

Just call list.__init__(self) to initialize self using the initialized from
the list class.



>  if fill: #auto-fill, useful to generate a new, unshuffled deck
>   for i in range(1, 14):
>    for j in range(1, 5):
>     self.append(Card(i, j))
>    #end for
>   #end for
>   self=self[:size] #keep only the amount specified
>

The same thing goes on here, you can't re-assign self.  Instead, you can
alter it in place by doing self[:] = self[:size].  That's called slice
assignment.  There's some discussion of this here:
http://docs.python.org/release/2.5.2/ref/assignment.html and
http://docs.python.org/library/stdtypes.html#mutable-sequence-types



>  elif cards is not None: #fill the pile with the cards
>   for c in cards:
>    self.append(c)
>   #end for
>  #end if
>  #end def __init__
>


I don't have a Card class built, but here's an example that uses tuples
instead:

class Pile(list):
    def __init__(self, size=52, cards=None, fill=False):
        list.__init__(self) #Initialize self as an empty list
        if fill:
            for i in range(1, 14):
                for j in range(1, 5):
                    self.append((i,j))
            self[:] = self[:size]
        elif cards is not None:
            for c in cards:
                self.append(c)

I think that supports all the same things you had in your example.

-- 
Jerry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100804/1164bb06/attachment.html>


More information about the Tutor mailing list