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()
x()
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)
s = Spam()
However, I do not understand how s()it was not called, but the method was called __call__. How it works?
source
share