I am trying to subclass an object setin Python using code similar to the one below, but I cannot use a reasonable definition __repr__to use.
class Alpha(set):
def __init__(self, name, s=()):
super(Alpha, self).__init__(s)
self.name = name
I would like to define __repr__in such a way as to get the following result:
>>> Alpha('Salem', (1,2,3))
Alpha('Salem', set([1, 2, 3]))
However, if I do not override __repr__, the output that I get ignores the value name...
>>> Alpha('Salem', (1,2,3))
Alpha([1, 2, 3])
... while, if I override __repr__, I cannot directly access the values in the set without creating a new instance of the set:
class Alpha(set):
…
def __repr__(self):
return "%s(%r, %r)" % (self.__class__.__name__, self.name, set(self))
This works, but creating a new instance of the set for __repr__, which will then be deleted, seems awkward and inefficient for me.
__repr__ ?
. , : . , ( - __repr__ - ), .
class Alpha(set):
def __init__(self, name, s=()):
super(Alpha, self).__init__(s)
self.name = name
self._set = set(s)
def __repr__(self):
return "%s(%r, %r)" % (self.__class__.__name__, self.name, self._set)