Methods "__" or "Dunder" in Python, which are the most used?


In Python there are "Magic" methods, such as __len__ , which allows the use of len (object), in addition to that in specific, which are the others most used that can facilitate the use of the structure? >     

asked by anonymous 10.01.2017 / 15:57

1 answer


Special or magic methods in Python are used to define a specific behavior for a class when a given operation is performed.

For example, there are situations where you can define behavior when the object of this class is treated as str or even float . There are still other cases where you can define behaviors when the object is called as a function, if it is used in comparison operations or mathematical operations. Anyway, Python has offered a wide range of special methods so you can customize the behavior of your class.

The list of magic methods that can be used in Python is very large . So I'll just post a few examples here:


Is invoked when the object is invoked as str .


class MyClass(object):
    def __str__(self):
        return 'is my class'

obj = MyClass();

print("This " + str(obj))

The result will be: "This is my class"


Is invoked when the object is invoked as a function.

class MyClass(object):
    def __call__(self):
        return 'Hello World!'

obj = MyClass();


Result is "Hello World!"


Used to initialize the class.


class Person(object):
    def __init__(self, name): = name   

p = Person('Wallace');


Result: "Wallace"


When you define this method, your class will have the behavior determined by it when there is an attempt to use the instance of that class as type float .


class Numero(object):

    def __float__(self):
        return 1.11111


The result will be: 1.11111

I think that having examples of __str__ and __float in my answer, it becomes unnecessary to speak of the existence of __int__ , __bytes__ , __dict__ , since they will work in similar ways for each type .

Other Methods

There are also several magic methods used to customize comparison operations.

  • __lt__ : Less than
10.01.2017 / 16:01