python repr for classes

  • Last Update :
  • Techknowledgy :

Let’s make a class, Person, and define the __repr__ method. We can then call this method using the built-in Python function repr().,In Python, __repr__ is a special method used to represent a class’s objects as a string. __repr__ is called by the repr() built-in function. You can define your own string representation of your class objects using the __repr__ method.,Ideally, the representation should be information-rich and could be used to recreate an object with the same value.,According to the official documentation, __repr__ is used to compute the “official” string representation of an object and is typically used for debugging.

# A simple Person class

class Person:
   def __init__(self, name, age):
   self.name = name
self.age = age

def __repr__(self):
   rep = 'Person(' + self.name + ',' + str(self.age) + ')'
return rep

# Let 's make a Person object and print the results of repr()

person = Person("John", 20)
print(repr(person))

Suggestion : 2

The __repr__ dunder method defines behavior when you pass an instance of a class to the repr().,The __repr__ method returns the string representation of an object. Typically, the __repr__() returns a string that can be executed and yield the same value as the object.,When a class doesn’t implement the __str__ method and you pass an instance of that class to the str(), Python returns the result of the __repr__ method because internally the __str__ method calls the __repr__ method:,The __str__ method returns a string representation of an object that is human-readable while the __repr__ method returns a string representation of an object that is machine-readable.

First, define the Person class with three instance attributes first_name, last_name, and age:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
class Person:
   def __init__(self, first_name, last_name, age):
   self.first_name = first_name
self.last_name = last_name
self.age = ageCode language: Python(python)

Second, create a new instance of the Person class and display its string representation:

person = Person('John', 'Doe', 25)
print(repr(person)) Code language: Python(python)

Output:

< __main__.Person object at 0x000001F51B3313A0 > Code language: HTML, XML(xml)

When you pass an instance of the Person class to the repr(), Python will call the __repr__ method automatically. For example:

person = Person("John", "Doe", 25)
print(repr(person)) Code language: Python(python)

For example:

person = Person('John', 'Doe', 25)
print(person) Code language: Python(python)

Suggestion : 3

Let’s look at a built-in class where both __str__ and __repr__ functions are defined.

>>>
import datetime
   >>>
   now = datetime.datetime.now() >>>
   now.__str__()
'2020-12-27 22:28:00.324317' >>>
now.__repr__()
'datetime.datetime(2020, 12, 27, 22, 28, 0, 324317)'

It’s clear from the output that __str__() is more human friendly whereas __repr__() is more information rich and machine friendly and can be used to reconstruct the object. In fact, we can use repr() function with eval() to construct the object.

>>> now1 = eval(repr(now)) >>>
   now == now1
True

Both of these functions are used in debugging, let’s see what happens if we don’t define these functions for a custom object.

class Person:

   def __init__(self, person_name, person_age):
   self.name = person_name
self.age = person_age

p = Person('Pankaj', 34)

print(p.__str__())
print(p.__repr__())

As you can see that the default implementation is useless. Let’s go ahead and implement both of these methods.

class Person:

   def __init__(self, person_name, person_age):
   self.name = person_name
self.age = person_age

def __str__(self):
   return f 'Person name is {self.name} and age is {self.age}'

def __repr__(self):
   return f 'Person(name={self.name}, age={self.age})'

p = Person('Pankaj', 34)

print(p.__str__())
print(p.__repr__())

Suggestion : 4

Last Updated : 25 Nov, 2020

Output:

Hello, Geeks.
0.181818181818

Output:

'Hello, Geeks.'
0.18181818181818182

Output:

Hello, Geeks.
0.181818181818

Suggestion : 5

In this tutorial, we will learn about the Python repr() function with the help of examples.,The repr() function returns a printable representational string of the given object.,The repr() function returns a printable representation of the given object.,Here, we assign a value 'foo' to var. Then, the repr() function returns "'foo'", 'foo' inside double-quotes.

Example

numbers = [1, 2, 3, 4, 5]

# create a printable representation of the list
printable_numbers = repr(numbers)
print(printable_numbers)

# Output: [1, 2, 3, 4, 5]

Example

numbers = [1, 2, 3, 4, 5]

# create a printable representation of the list
printable_numbers = repr(numbers)
print(printable_numbers)

# Output: [1, 2, 3, 4, 5]

The syntax of repr() is:

repr(obj)

Example 1: How repr() works in Python?

var = 'foo'

print(repr(var))

When the result from repr() is passed to eval(), we will get the original object (for many types).

>>> eval(repr(var))
'foo'

You can easily implement/override __repr__() so that repr() works differently.

class Person:
   name = 'Adam'

def __repr__(self):
   return repr('Hello ' + self.name)

print(repr(Person()))

Suggestion : 6

Some classes have built-in "special" methods associated with them, which can be identified by 2 underscores before and after the method name, like __repr__.,As we mentioned, Python classes offer "special methods", which allow us to implement different kinds of behaviors with classes.,Method - A method is a function inside a class, which defines a behavior of objects created from the class.,Special methods allow you to use Python's built-in functionality with the objects you create. Special methods are can easily be identified as their names start end with double underscores, like __specialMethodName__().

Let's look at an example:

class Thing:
   attr1 = 0
attr2 = 1

def getAttr1(self):
   return self.attr1

Here, you have a Thing class with two attributes attr1 and attr2 and a method getAttr1. The method has a single argument self, which refers to the instance once it's created, and all methods in a class should always have the self as their first argument. You can create instances from the class by calling the class much like you would a function, and assigning to a variable:

instance1 = Thing()
instance2 = Thing()

We can call instance methods like so:

>>> instance1.getAttr1()
0

Let's see how this works:

>>> inst1 = Thing2(5)
Initializing instance...
   >>>
   inst1.get_a()
5

Now let's look at a real-world example of how you can use built-in functions with the objects by defining a Book class with the attributes name and the total number of pages, totalPages. First, let's define a class Book and an instance of the class:

class Book:
   def __init__(self, name, totalPages):
   self.name = name
self.totalPages = totalPages

Suggestion : 7

The repr() function returns the string representation of the value passed to eval function by default. For the custom class object, it returns a string enclosed in angle brackets that contains the name and address of the object by default.,The repr() method returns a string containing a printable representation of an object. The repr() function calls the underlying __repr__() function of the object.,obj: Required. The object whose printable representation is to be returned., TutorialsTeacher.com is optimized for learning web technologies step by step. Examples might be simplified to improve reading and basic understanding. While using this site, you agree to have read and accepted our terms of use and privacy policy.

Syntax:

repr(obj)
2._
print(repr(10))
print(repr(10.5))
print(repr(True))
print(repr(4 + 2))
3._
'10'
'10.5'
'True'
'6'
5._
'<main.student object at 0x0000000003B1FF98>'
6._
class student:
   name = ''
def __repr__(self):
   return 'student class'

std = student()
repr(std)
print(repr(10))
print(repr(10.5))
print(repr(True))
print(repr(4 + 2))
'10'
'10.5'
'True'
'6'
class student:
   name = ''

std = student()
repr(std)
'<main.student object at 0x0000000003B1FF98>'
class student:
   name = ''
def __repr__(self):
   return 'student class'

std = student()
repr(std)

Suggestion : 8

Instead of building your own class-to-string conversion machinery, modelled after Java’s toString() methods, you’ll be better off adding the __str__ and __repr__ “dunder” methods to your class. They are the Pythonic way to control how objects are converted to strings in different situations. You can learn more about this in the Python data model documentation.,You can control to-string conversion in your own classes using the __str__ and __repr__ “dunder” methods. Writing your own Java-esque “tostring” methods is considered unpythonic.,You might find yourself trying to work around this by printing attributes of the class directly, or even by adding a custom to_string() method to your classes:,To manually choose between both string conversion methods, for example, to express your code’s intent more clearly, it’s best to use the built-in str() and repr() functions. Using them is preferable over calling the object’s __str__ or __repr__ directly, as it looks nicer and gives the same result:

class Car:
   def __init__(self, color, mileage):
   self.color = color
self.mileage = mileage

   >>>
   my_car = Car('red', 37281) >>>
   print(my_car) <
   __console__.Car object at 0x109b73da0 >
   >>>
   my_car <
   __console__.Car object at 0x109b73da0 >
>>> print(my_car.color, my_car.mileage)
red 37281
class Car:
   def __init__(self, color, mileage):
   self.color = color
self.mileage = mileage

def __str__(self):
   return f 'a {self.color} car'
>>> my_car = Car('red', 37281) >>>
   print(my_car)
'a red car' >>>
my_car
   <
   __console__.Car object at 0x109ca24e0 >
>>> print(my_car)
a red car
   >>>
   str(my_car)
'a red car' >>>
'{}'.format(my_car)
'a red car'
class Car:
   def __init__(self, color, mileage):
   self.color = color
self.mileage = mileage

def __repr__(self):
   return '__repr__ for Car'

def __str__(self):
   return '__str__ for Car'