6.3 Python Special Functions
Let's dive into the special functions in Python, also known as "magic" or "dunder" methods. These methods provide a simple way to make your classes act like built-in types. This means you can use type-specific functions (like len or +) with your objects. You've already seen these in use with the __init__ method for classes. Let's explore more:
1. __str__ and __repr__ Methods
The __str__ and __repr__ methods in Python represent the class objects as a string – they are methods for string representation of a class. The __str__ method in Python represents the class objects as a human-readable string, while the __repr__ method is meant to be an unambiguous representation of the object, and should ideally contain more detail than __str__. If __repr__ is defined, and __str__ is not, the objects will behave as though __str__=__repr__.
2. __add__ and __sub__ Methods
These methods are used to overload the + and - operator...