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

Asked

Viewed 4,201 times

10

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

1 answer

12

Special or magic methods in Python are used to define a class-specific behavior when a certain operation is operated.

For example, there are situations where you can define a behavior when the object of that class is treated as str or as 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 magical methods that can be used in Python is biggie. So I’m going to post just a few examples here:

__str__

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

It is used to initialize the class.

Example:

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


p = Person('Wallace');

print(p.name)

Upshot: "Wallace"

__float__

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

Behold:

class Numero(object):

    def __float__(self):
        return 1.11111



print(float(Numero()))

The result will be: 1.11111

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

Other methods

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

  • __lt__: Smaller than (Less than)
  • __le__: Less or equal (Less or Equal)
  • __eq__: Equal (equals)
  • __ne__: Not equal (not Equal)
  • __ge__: Greater or equal (greather or Equal)
  • __gt__: - Greater than (greather than)

All of the above methods are invoked when you use a comparative expression. Generally, they receive a parameter that should be compared with a value of the current class.

Example __eq__:

class Numero(object):
    def __init__(self, numero):
        self.numero = numero   

    def __eq__(self, a):
        print("Chamou __eq__")
        print(a.numero)


a = Numero(1)
b = Numero(2)

a == b
b == a

The result will be:

"Chamou __eq__"
2
"Chamou __eq__"
1

Read more on Standard Operators as Function

  • Already won my +1, but I suggest supplementing the answer with some very simple examples. :)

  • 1

    @Luizvieira I am elaborating :p

  • Just one detail, the "init" is an initiator, the "new" is a builder, these most basic I know, already the comparison I did not know.

  • @Arthursilva I didn’t know about __new__, kkkk

  • Guys, I need to get back to work now. Anything, just say it, I’ll edit it later.

  • @Miguel can edit, I really thought about it. Now I’m a little out of time :p

  • What would be the point of you passing the self as a method parameter __init__() explicitly?

  • @lucasmoraes, this is part of the Python specification. "Better explicit than implicit"

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.