
PYTHON — Default Methods in Python
Technology is best when it brings people together. — Matt Mullenweg
Insights in this article were refined using prompt engineering methods.

PYTHON — Modifying Change List in Python
## Default Methods in Python
In Python, default methods are inherited by all objects. They provide default behavior for certain operations and can be overridden to customize their functionality.
The __str__ Method
In Python, the __str__ method is similar to the .toString() method in Java. It provides a string representation of an object and is used when the str() function is called on the object.
Here’s an example of how to override the __str__ method for a Car class:
class Car:
def __init__(self, color, model, year):
self.color = color
self.model = model
self.year = year
def __str__(self):
return f"My car is a {self.color} {self.model} from {self.year}"
my_car = Car("red", "Toyota", 2020)
print(str(my_car))When str(my_car) is called, the overridden __str__ method is invoked, providing a customized string representation of the my_car object.
The __repr__ Method
In addition to __str__, Python also provides the __repr__ method, which is used for generating a string representation of an object for debugging purposes. It can be overridden to provide a technical representation of the object.
Here’s an example of how to override the __repr__ method for the Car class:
class Car:
# ... (same as above)
def __repr__(self):
return f"Car(color={self.color}, model={self.model}, year={self.year})"
my_car = Car("red", "Toyota", 2020)
print(repr(my_car))When repr(my_car) is called, the overridden __repr__ method is invoked, providing a technical representation of the my_car object.
Other Dunder (Double Underscore) Methods
Python provides various other dunder methods, such as __hash__ and __eq__, which are used for hashing and equality comparison, respectively.
Here’s an example of how to override the __eq__ method for the Car class to enable custom comparison:
class Car:
# ... (same as above)
def __eq__(self, other):
return self.color == other.color and self.model == other.model and self.year == other.year
my_car1 = Car("red", "Toyota", 2020)
my_car2 = Car("red", "Toyota", 2020)
print(my_car1 == my_car2) # Output: TrueIn this example, the __eq__ method is overridden to compare the color, model, and year attributes of two Car objects.
Conclusion
In Python, default methods provide a way to define custom behavior for operations such as string representation, debugging, hashing, and comparison. By understanding and overriding these methods, you can customize the behavior of your classes to suit your specific requirements.







