Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
The __repr__()
method in Python is a special method used to define the "official" string representation of an object. It's called by the built-in repr()
function and used by the interpreter to display the object when you type its name in an interactive session. The goal of the __repr__()
method is to provide an unambiguous string representation of the object, which ideally should allow you to recreate the object if you were to pass the string to the eval()
function.
In this tutorial, we'll show you how to define and use the __repr__()
method in Python:
__repr__()
method:
Create a class with an __init__()
method to initialize some instance attributes.class Person: def __init__(self, name, age): self.name = name self.age = age
person = Person("Alice", 30) print(person) # Output: <__main__.Person object at 0x7f8c48527400>
The default string representation of the object is not very informative.
__repr__()
method:
Create a class with an __init__()
method, some instance attributes, and a custom __repr__()
method. The __repr__()
method should return a string that represents the object.class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"Person('{self.name}', {self.age})"
__repr__()
method:
Instantiate the class to create an object with specific attribute values.person = Person("Alice", 30) print(person) # Output: Person('Alice', 30)
The custom string representation provided by the __repr__()
method is more informative and can be used to recreate the object.
repr()
function with the custom class:
The repr()
function calls the __repr__()
method of the object passed as an argument.person_repr = repr(person) print(person_repr) # Output: "Person('Alice', 30)"
In this tutorial, you learned how to define and use the __repr__()
method in Python to provide a clear and unambiguous string representation of your custom objects. Implementing a custom __repr__()
method can improve the readability and usability of your classes, making it easier to understand and debug your code.
Python repr
method for displaying object attributes:
The __repr__
method is used to define the string representation of an object for development and debugging purposes.
class MyClass: def __init__(self, attribute): self.attribute = attribute def __repr__(self): return f"MyClass(attribute={self.attribute})" obj = MyClass(attribute="example") print(repr(obj)) # Output: MyClass(attribute=example)
Creating a custom repr
method in Python:
class CustomClass: def __init__(self, attribute): self.attribute = attribute def __repr__(self): return f"CustomClass(attribute={self.attribute})" obj = CustomClass(attribute="custom") print(repr(obj)) # Output: CustomClass(attribute=custom)
Using repr
to improve object representation in Python:
class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"Point(x={self.x}, y={self.y})" p = Point(x=1, y=2) print(repr(p)) # Output: Point(x=1, y=2)
Customizing the string representation of objects with repr
:
class CustomObject: def __init__(self, data): self.data = data def __repr__(self): return f"CustomObject(data={self.data})" obj = CustomObject(data=[1, 2, 3]) print(repr(obj)) # Output: CustomObject(data=[1, 2, 3])
Displaying private attributes in repr
in Python:
class PrivateAttributes: def __init__(self): self._private_data = "sensitive" def __repr__(self): return f"PrivateAttributes(_private_data={self._private_data})" obj = PrivateAttributes() print(repr(obj)) # Output: PrivateAttributes(_private_data=sensitive)
Dynamic attribute representation with repr
in Python:
class DynamicAttributes: def __init__(self, **kwargs): self.__dict__.update(kwargs) def __repr__(self): attributes = ', '.join(f"{key}={value}" for key, value in self.__dict__.items()) return f"DynamicAttributes({attributes})" obj = DynamicAttributes(attr1="value1", attr2="value2") print(repr(obj)) # Output: DynamicAttributes(attr1=value1, attr2=value2)
Using repr
for pretty-printing in Python:
class PrettyPrint: def __init__(self, data): self.data = data def __repr__(self): return pprint.pformat(self.data) obj = PrettyPrint(data={"key": "value", "nested": {"inner": "data"}}) print(repr(obj)) # Output: {'key': 'value', 'nested': {'inner': 'data'}}