Defining
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?
我怀疑以下方法可行:
def __repr__(self):
return 'set([%s])' % ', '.join(self)
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]
像这样简单的事情可能会足够好,并会照顾这两种方法:
class Set(object):
def __init__(self):
self.array = ...
def __repr__(self):
return '{}({!r})'.format(self.__class__.__name__, self.array)
__str__ = __repr__
链接地址: http://www.djcxy.com/p/28306.html
下一篇: 定义