Python repr() Built in Function
The repr() function is used to return a printable representation of the given object. The syntax of this function is:
repr(object)
The object parameter is required and specifies the object whose representation is needed. The repr() function returns a string that can be evaluated by eval() function to recreate the original object.
The repr() function can be useful for debugging and logging purposes, as it shows more details about the object than str() function. It can also be used to customize the representation of user-defined classes by overriding the repr() method. Here are some examples of using the repr() function in Python:
To get the representation of a built-in type such as list:
x = [1, 2, 3]
print(repr(x)) # prints '[1, 2, 3]'
To get the representation of a custom class without overriding repr() method:
class Student:
def __init__(self, name):
self.name = name
s = Student("Alice")
print(repr(s)) # prints '<__main__.Student object at 0x000001F66D11DBE0>'
To get the representation of a custom class with overriding repr() method:
class Student:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Student(name={self.name})"
s = Student("Alice")
print(repr(s)) # prints 'Student(name=Alice)'
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment