Python中类的callable属性指什么?相关代码问题求解
Understanding Callables in Python: Classes vs. Their Instances
Let’s break down your questions step by step, using your code as a reference:
Why is class A callable, but its instance a not?
- In Python, classes are callable by default because they inherit the
__call__method from their metaclass (the default istypefor all standard classes). When you runA(), you’re actually invokingA.__call__()—this method handles the full instance creation process: first calling__new__to allocate memory for the object, then__init__to initialize its state. That’s whycallable(A)returnsTrue. - In contrast, an instance of a class is only callable if the class defines a custom
__call__method. Your classAdoesn’t have one, so when you try to runa(), Python throws aTypeError—the instance has no logic to handle being invoked like a function.
What’s going on with A.__call__()?
When you run print(type(A.__call__())) and get <class '__main__.A'>, here’s why:
A.__call__()is exactly equivalent to callingA()—it triggers the instance creation workflow. The__call__method of the class returns a new instance ofA, so the type of that return value is naturally theAclass itself.- To answer your direct question: Yes, every time you instantiate with
A(), you are indirectly callingA.__call__(). Behind the scenes, Python translatesA(*args, **kwargs)totype.__call__(A, *args, **kwargs), which in turn callsA.__new__()to create the object andA.__init__()to set it up.
Example: Making an instance callable
If you want your instance a to be callable, just add a __call__ method to the class:
class A(object): def __init__(self): pass def __call__(self): print("Instance a is now callable!") print("Is A callable? " + str(callable(A))) # Output: Is A callable? True a = A() print("created a") a() # Output: Instance a is now callable!
内容的提问来源于stack exchange,提问作者Kevin L.
相关产品推荐
相关产品推荐

