Does the __repr()__ method need to provide all the attributes of an object?


#1

Question

When implementing the __repr__() method, do all object attributes have to be used when constructing the string?

Answer

While you are allowed to include or exclude any information from the object that you want, the Python documentation recommends that the implementation for __repr__() should contain as much information as possible and if, at all possible, it should contain whatever is necessary to recreate the object. The __str__() method also returns a string representing the object but it can be used for a more informal representation of the object.


#2

In a sense, instance.__repr__() is a getter, only it gets everything, and the expected return value will be a string representation of the data points of the instance as initialized and or modified.

The operative phrase above was return value. Getters don’t do things; they return things.

class Foo(object):
  def __init__(self, foo):
    self.foo = foo
  def __repr__(self):
    return "foo: {}".format(self.foo)

foo = Foo('foo')
print (foo)
>>> 
=================== RESTART: D:/cc/discuss/FAQ/__repr__.py ===================
foo: foo
>>>