What is the use of `__repr__`?

in the: Lesson

What is the use of the dunder __repr__?

class Employee():
  def __init__(self, name):
    self.name = name

  def __repr__(self):
    return self.name

argus = Employee("Argus Filch")
print(argus)
# prints "Argus Filch"

Only, that I can access the object attributes directly, after the object initiation?

instead, I can use:
either:

def repr(self):
  return self.name.

and then, call outside the class:
print(argus.repr())
else:
print(argus.name)

The thing about dunder methods is that you can call them using something other than the method name. for instance,__add__(self, y) can be called by an object, say argus, as argus + y, and you can thus define what the + operator does in your class.

In the case of __repr__(), you can control what is printed if the user types print(argus), which is one way the method can be called: no dot notation required.

8 Likes

Thank you. I didn’t completely understand what advantages does it contain. Hope, to do it in the future.

8 Likes

Does all the dunder methods run when an object is called? no right? because we didn’t call the repr method , but string is printed.