從我的理解類內部__call__
方法瞭解__call__實現函數調用操作符,例如:使用元類
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"
不過,我經歷的Python Cookbook和作家定義的元類控制實例創建,以便您不能直接實例化對象。這是他如何做的:
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
不過,我不明白的是s()
是如何不叫,但它的__call__
方法被調用。這個怎麼用?
偉大而簡單的答案! 。如果OP想要更多的東西:https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/ –
謝謝。這正是我一直在尋找的! – electro7912