[Tutor] access class through indexing?

Dave Angel davea at ieee.org
Thu Aug 5 00:30:56 CEST 2010

Alex Hall wrote:
> On 8/4/10, Evert Rol <evert.rol at gmail.com> wrote:
>> <snip>
>> That depends how you create the Pile of 52 cards: list(52) also doesn't
>> generate 52 (random) items.
>> If you override __init__ to accept an integer that generates the cards for
>> you, this should work.
> 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=[]
>   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
>   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__
You have two serious problems here, and maybe others, I didn't keep looking.

Since you never call super(), the init of the base class never happens.  
It may happen to work, since you're apparently willing to take its 
default behavior, but I don't know.  But even worse, you never even talk 
to your own object.  The first parameter to __init__() is a ref to the 
actual object you're supposed to be initializing, and you immediately 
overwrite it (self) with another object.  As a result, everything else 
you do in that method is thrown out when the method returns.  Remove 
that line

self = []


More information about the Tutor mailing list