What are Python's magic methods (e.g., `__init__`, `__str__`)?

In Python, magic methods are special methods that begin and end with double underscores. These methods allow you to define how objects of your class behave in various situations. Some common magic methods include:

1. `__init__(self, ...)`: This method is used to initialize a newly created object. It is called when you create a new instance of a class.

2. `__str__(self)`: This method is called when the `str()` function is used on an object. It should return a string representation of the object.

3. `__repr__(self)`: This method is called when the `repr()` function is used on an object. It should return an unambiguous string representation of the object for debugging.

4. `__len__(self)`: This method is used to define the behavior of the `len()` function on your object.

5. `__getitem__(self, key)`: This method allows you to use indexing to retrieve items from your object, like `obj[key]`.

6. `__setitem__(self, key, value)`: This method allows you to use indexing to set items in your object, like `obj[key] = value`.

7. `__delitem__(self, key)`: This method allows you to use the `del` statement to delete items from your object, like `del obj[key]`.

These magic methods provide a way to customize the behavior of your objects and make your classes more powerful and flexible.
What are Python's magic methods (e.g., `__init__`, `__str__`)?

Related Questions