I am wondering how to implement the __repr__
method for a class with __slots__
. As far as I understand __repr__
, it is supposed to return a string which can be used to construct the object of which we called __repr__
. In other words, giving repr(object)
to a Python interpreter should construct object
.
However, if there is a class having __slots__
, I find it hard to imagine how to implement this. This is because when using __slots__
, some of the attributes in slots may be initialised and have values, others probably won't. So how do I figure out which attributes were initialised and there values to pass them to the __repr__
string?
Minimal example of such a class:
class TestClass:
__slots__ = 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', '__dict__'
def __init__(self, something, something_else, **kwargs):
self.something = something
self.something_else = something_else
for key, value in kwargs.items():
setattr(self, key, value)
def __repr__(self):
return '%s(%r, %r)' %(self.__class__.__name__, self.something, self.something_else)
Any suggestions?