The built-in function repr() in Python

Overview:

  • The Python built-in function repr() returns the string representation of an object.

Example:

The Python code example below prints the string representation for an integer, a floating point number and an object of user defined class Banner. For the Banner object, the representation comes from the __repr__() method implemented in the Banner class.

# Example Python program that prints
# the string reprsentation of objects
# belonging to various types
class Banner:
    def __init__(self, msg):
        self.msg = msg

    def display(self):
        print(contents)

    def __repr__(self):        
        return "<type:%s,id:%d,msg:%s>"%(__class__.__name__,id(self),self.msg)

# Get info about an int object
val = 10
print(repr(val))
print(repr(type(val)))

# Get info about a floating point object
val = 10.1
print(repr(val))
print(repr(type(val)))

# Get info about an instance of an user defined class
simpleBanner = Banner("Hello World")
print(repr(simpleBanner))

Output:

10
<class 'int'>
10.1
<class 'float'>
<type:Banner,id:4401581648,msg:Hello World>

 


Copyright 2024 © pythontic.com