Home > Mobile >  Python - Print which dunder methods were called when creating an object
Python - Print which dunder methods were called when creating an object

Time:04-03

I came across the following code, which looks easy but was a little bit of black magic for me:

class FileItem(dict):
    def __init__(self, name):
        dict.__init__(self, name=name)

x = FileItem("test")
print(x)

{'name': 'test'}

The same seems to be happening when I do this:

print(dict.__call__(name="test"))

{'name': 'test'}

I think there also has to be at least the __init___ method be called in the second example, right? Is there a way to print all dunder methods used to create an Object?

From my understanding right now it seems it is:

  1. __new__
  2. __init__
    Optional: __call__

Can anyone help me how to actually see this in action?

CodePudding user response:

__call__ is only indirectly part of object creation. Your example doesn't do exactly what you think it does -- it does not call dict.__call__. That would only be called if you did x() where x is a dict instance.

dict happens to be an object itself, of type class. The class type has a __call__ method, which allows you to write x = dict(). The class.__call__ method triggers object creation.

Object creation involves __new__ and __init__.

  • Related