Artificial Intelligence
Please fill the required field.

explain __str__ method in python with example


In Python, the `__str__` method is a special method used to define a human-readable string representation of an object. When you call the `str()` function on an object or use the `print()` function with that object, Python internally calls the object's `__str__` method to get a string representation of it. If a class does not implement a `__str__` method, Python will use the default implementation from the base `object` class, which typically returns a string that includes the object's type and its memory address. Here's how you can define and use the `__str__` method with a simple example: ```python class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f'{self.name}, Age: {self.age}' # Creating an instance of the Person class person = Person("Alice", 30) # Using print() function to display the person's information print(person) # This will call person.__str__() ``` ### Explanation 1. **Class Definition**: We define a `Person` class with an `__init__` method that initializes the `name` and `age` attributes. 2. **`__str__` Method**: We implement the `__str__` method to return a formatted string that combines the person's name and age. 3. **Creating an Instance**: We create an instance of `Person` named `Alice` who is 30 years old. 4. **Printing the Instance**: When we use `print(person)`, Python calls the `__str__` method, which returns the string representation "Alice, Age: 30". ### Output: ``` Alice, Age: 30 ``` Using the `__str__` method is beneficial for debugging and logging, as it provides a user-friendly way to represent complex objects. If you only want to provide more technical (or formal) information about the object (for developers), you might consider implementing the `__repr__` method in addition to or instead of `__str__`.