Understanding __call__ with metaclasses

In my opinion, a method __call__inside a class implements a function call operator, for example:

class Foo:
    def __init__(self):
        print("I'm inside the __init__ method")

    def __call__(self):
        print("I'm inside the __call__ method")

x = Foo() #outputs "I'm inside the __init__ method"
x() #outputs "I'm inside the __call__ method"

However, I am looking at the Python Cookbook , and the author has defined a metaclass to control instantiation so that you cannot instantiate the object directly. Here's how he did it:

class NoInstance(type):
    def __call__(self, *args, **kwargs):
        raise TypeError("Can't instantaite class directly")


class Spam(metaclass=NoInstance):
    @staticmethod
    def grok(x):
        print("Spam.grok")

Spam.grok(42) #outputs "Spam.grok"

s = Spam() #outputs TypeError: Can't instantaite class directly

However, I do not understand how s()it was not called, but the method was called __call__. How it works?

+4
source share
2 answers

Metaclasses implement class behavior (not instance). Therefore, when you look at instantiating:

x = Foo()

"" Foo. __call__ , __new__ __init__ .


@Take_Care_ , ionelmc " Python". :

enter image description here

.

+2

- . metaclass __call__(), , , , .. , .

+1

Source: https://habr.com/ru/post/1683124/


All Articles