Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special (magic) methods in Python [closed]

Tags:

python

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.

like image 653
ibz Avatar asked Jul 07 '09 06:07

ibz


People also ask

What are the __ methods in Python?

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.

What are the magic methods in Python?

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.

Is __ init __ a magic method?

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.

What does __ add __ do in Python?

__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.


1 Answers

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).

like image 150
David Cournapeau Avatar answered Sep 27 '22 21:09

David Cournapeau