What are all the special (magic) methods in Python? The __xxx__
methods, that is.
I'm often looking for a way to override something which I know is possible to do through one of these methods, but I'm having a hard time to find how since as far as I can tell there is no definitive list of these methods, PLUS their names are not really Google friendly. So I think having a list of those here on SO would be a good idea.
The __call__ method enables Python programmers to write classes where the instances behave like functions. Both functions and the instances of such classes are called callables.
Magic methods in Python are the special methods that start and end with the double underscores. They are also called dunder methods. Magic methods are not meant to be invoked directly by you, but the invocation happens internally from the class on a certain action.
Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc.
__add__ magic method is used to add the attributes of the class instance. For example, let's say object1 is an instance of a class A and object2 is an instance of class B and both of these classes have an attribute called 'a', that holds an integer.
At the python level, most of them are documented in the language reference. At the C level, you can find it under the object protocol section (strictly speaking, you only have a subset here, though).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With