YouTip LogoYouTip

Python Func Repr

# Python repr() Function The `repr()` function is a built-in Python function used to obtain a string representation of an object. This representation is typically designed to be unambiguous and, when possible, should match the valid Python code required to recreate the object. --- ## Description The `repr()` function converts an object into a string format suitable for the Python interpreter to read. It is primarily used for debugging and development, as it provides a precise, detailed representation of an object's state. --- ## Syntax The syntax for the `repr()` method is as follows: ```python repr(object) ``` ### Parameters * **`object`**: The object whose string representation you want to retrieve (e.g., strings, dictionaries, custom class instances, etc.). ### Return Value Returns a string containing a printable representation of the object. --- ## Basic Examples Here is how `repr()` behaves with built-in Python data types: ```python >>> s = 'RUNOOB' >>> repr(s) "'RUNOOB'" >>> my_dict = {'runoob': 'runoob.com', 'google': 'google.com'} >>> repr(my_dict) "{'runoob': 'runoob.com', 'google': 'google.com'}" ``` --- ## Advanced Usage: `repr()` vs `str()` In Python, both `repr()` and `str()` convert objects to strings, but they serve different purposes: * **`str(object)`**: Designed to return a user-friendly, readable string representation of the object. It is meant for end-users. * **`repr(object)`**: Designed to return an unambiguous representation of the object, mainly for developers and debugging. For many types, `eval(repr(obj)) == obj` is true. ### Code Comparison ```python import datetime today = datetime.datetime.now() # str() shows a readable format for end-users print(str(today)) # Output: 2023-10-27 14:30:00.123456 # repr() shows the exact constructor representation for developers print(repr(today)) # Output: datetime.datetime(2023, 10, 27, 14, 30, 0, 123456) ``` --- ## Implementing `__repr__()` in Custom Classes You can control what `repr()` returns for your custom classes by overriding the special `__repr__()` method. ### Example ```python class Person: def __init__(self, name, age): self.name = name self.age = age # Define the developer-friendly string representation def __repr__(self): return f"Person(name={self.name!r}, age={self.age})" # Create an instance p = Person("Alice", 30) # Call repr() on the instance print(repr(p)) # Output: Person(name='Alice', age=30) ``` *Note: In the f-string above, `{self.name!r}` automatically calls `repr()` on the `self.name` string, ensuring it is wrapped in quotes inside the output.*
← Python Func CompilePython Func Ord β†’