1

I have been working on a large assignment and I'm almost finished except I need help writing the __str__ and __repr__ functions of a Set container.

I have never done this and I have no clue what to do. Searching the internet, I'm still stuck.

I've tried something like:

'%s(%r)' % (self.__class__, self)

I need to print out a representation like this:

'set([ELEMENT_1, ELEMENT_2,..., ELEMENT_N])'

My elements are stored in an array class that I wrote the set container around. I access it with a loop like for item in self or if item in self

Please help?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
Matt M
  • 149
  • 2
  • 4
  • 17
  • This might help you understand [Stack overflow page talking about the differences between __repr__ and __str__][1] [1]: http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python – Jroosterman Feb 12 '13 at 21:07

3 Answers3

1

I suspect the following would work:

def __repr__(self):
    return 'set([%s])' % ', '.join(self)
Ben
  • 6,687
  • 2
  • 33
  • 46
1

See this answer detailing the difference between __str__ and __repr__.

A basic implementation would be something like:

def __repr__(self):
    return 'set(%r)' % [item for item in self]
Community
  • 1
  • 1
Wesley Baugh
  • 3,720
  • 4
  • 24
  • 42
0

Something as simple as this may be good enough and would take care of both methods:

class Set(object):
    def __init__(self):
        self.array = ...

    def __repr__(self):
        return '{}({!r})'.format(self.__class__.__name__, self.array)

    __str__ = __repr__
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    "if `__repr__` is defined, and `__str__` is not, the object will behave as though `__str__=__repr__`." - [reference](http://stackoverflow.com/a/2626364/1988505) – Wesley Baugh Feb 13 '13 at 01:38
  • True enough. The main point though was the `{!r}` in the format string which will be replaced with the `repr(self.array)` which, of course, will depend on exactly what it is -- and makes it an object-oriented design. – martineau Feb 13 '13 at 07:26