FAQ: Learn Python: Classes - String Representation

This community-built FAQ covers the “String Representation” exercise from the lesson “Learn Python: Classes”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

FAQs on the exercise String Representation

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


# You are looking for:
return "Circle with radius {radius}".format(radius=self.radius) 

#but this also works :
return "Circle with {}".format(self.radius) 

:persevere:

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.

1 Like

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

1 Like