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

6

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

8

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:

__str__

Is invoked when the object is invoked as str .

Example:

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


obj = MyClass();

print("This " + str(obj))

The result will be: "This is my class"

__call__

Is invoked when the object is invoked as a function.

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


obj = MyClass();

print(obj())

Result is "Hello World!"

__init__

Used to initialize the class.

Example:

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


p = Person('Wallace');

print(p.name)

Result: "Wallace"

__float__

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 .

See:

class Numero(object):

    def __float__(self):
        return 1.11111



print(float(Numero()))

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