[Tutor] Str Method

Alan Gauld alan.gauld at btinternet.com
Thu Nov 1 18:11:10 CET 2012


On 01/11/12 15:34, Ashley Fowler wrote:
> Hello I am trying to add a str method to a Set ADT implementation to
> allow a user to print the contents of a set. However the resulting
> string should look like that of a list. except I am suppose to use curly
> brackets to surround the elements.
>
> For an example...
>>>> set1 = Set()
>>>> print(set1)
> {}
>
>
> Question is how do you implement the "curly brackets" in my str method?
>

Curly brackets are just characters like any other...

 >>> print( '{', 42, '}' )


> This is what I have so far...
>
> def __init__( self, *initElements ):
>      self._theElements = list()
>
> def __str__(self):
>       return self._theElements

You are returning a list. But __str__() is supposed to return a string.
You need to create a string representation of your data. There are many 
ways to do that depending on what you want it to look like or contain.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list