[Tutor] Str method

Dave Angel d at davea.name
Mon Nov 5 05:49:13 CET 2012


On 11/04/2012 09:01 PM, Ashley Fowler wrote:

(You top-posted, so I have to remove all the historical context, or
it'll remain out of order)

> I have code for a Set ADT. The Set ADT is a container that stores a collection of values or elements.
>
>
>
>
> Below is some of my code...I have run into two problems so far.
>
>
>
>
> First I have to modify  __init__ method so that new sets can be initialized to a list of elements. This modification adds a starred parameter, *initElements. 

Why?  How are you planning to use the data, that makes the * useful? 
You said you're planning to call it with a list.

Where are your examples of calling code, that'll create objects from
this class?

> But somehow I still need to initialize a list to several elements and I have no clue what to do. 

If you take out the star, then that's easy:

self._theElements = initElements
or perhaps
self._theElements = initElements[:]




> The other problem is I had to add the str method to allow a user to print the contents of the set... meaning I must construct a string from the elements of the set one by one, and with curly braces at the beginning and at the end.
>

You asked this in another thread, which had at least one correct answer
3 days ago.  Why repeat the question if you're not going to study the
replies?

>
>
> class Set :
>   
>   def __init__( self, *initElements ):
>     self._theElements = list()
>     
>   def __len__( self ):
>     return len( self._theElements )
>     
>   def __contains__( self, element ):
>     return element in self._theElements   
>     
>   def add( self, element ):                  
>     if element not in self :
>       self._theElements.append( element ) 
>       
>   def remove( self, element ):
>     assert element in self, "The element must be in the set."

This is abuse of the assert statement.  It's for finding bugs, not
validating data.  At the least you should do a raise here.

>     self._theElements.remove( item )
>
>
>
>
>   def __iter__( self ):
>     return _SetIterator( self._theElements )
>
>
>
>
>   def __str__(self):
>     for element in str(self._theElements):
>       return element

When you have an unconditional return in a loop, it'll only happen
once.  So you'll return the first element of the list.  See the other
thread with the same subject line that you started a few days ago.

>     
> <snip>
>

I'm also curious what's the intended connection between this class and
an actual set.

-- 

DaveA



More information about the Tutor mailing list