Skip to main content
 首页 » 编程设计

python之可调用类型的定义是什么

2025年02月15日7arxive

Background :我试图理解为什么静态和类方法在描述符时不可调用,而类的普通方法(即既不是静态方法也不是类方法的类方法)和不是类属性的函数都是描述符和可调用的。

在 Python 中,可调用类型的定义是什么?

  1. 来自 https://docs.python.org/3/reference/datamodel.html

    Callable types These are the types to which the function call operation (see section Calls) can be applied:

    “函数调用操作”的运算符是()吗?一个也是 可调用类型定义为其实例被函数调用的类型 operator () 可以应用于?

  2. 来自 https://docs.python.org/3/reference/expressions.html#calls

    The primary must evaluate to a callable object (user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class instances, and all objects having a __call__() method are callable).

    这是否意味着可调用类型可能有也可能没有 __call__() 方法?如果一个类有一个 __call__() 方法,那么它 必须是可调用类型?如果一个类没有 __call__() 方法,那么它可能是也可能不是可调用类型?

    做“用户自定义函数、内置函数、内置方法” 对象、类对象、类实例的方法”没有 __call__() 方法?它们是可调用类型的实例吗?什么 它们分别有哪些具体类型?

谢谢。

请您参考如下方法:

Is the operator for "the function call operatation" ()? So is a callable type defined as a type whose instances the function call operator () can be applied to?

是的,完全正确。

Does it mean that a callable type may or might not have a __call__() method? If a class has a __call__() method, then it must be a callable type? If a class doesn't have a __call__() method, then it might or might not be a callable type?

要使给定对象成为可调用对象,它必须定义 __call__ ,功能做,例如:

def foo(): 
    pass 
callable(foo) # True 

staticmethod的或classmethod s(接上一个问题),不要定义 __call__ :

s = staticmethod(foo) 
callable(s)  # False 

( callable 基本上做类似 getattr(foo, '__call__', False) 的事情)

Do "user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class instances" not have a call() method? Are they instances of callable types? What specific types do they have respectively?

  • 用户定义的函数( function 类型,如 foo )有 __call__ .

  • 内置函数(例如 max )也有 __call__ , 请参阅 callable(max) .

  • 内置对象的方法,是的:callable(str.isupper) .

  • 类对象,是的(type 为它们定义了一个 __call__):

    >>> class Spam: pass 
    >>> callable(Spam) # True 
    
  • 类实例的方法:

    >>> class Spam2:  
    ...     def do_spam(self): 
    ...         return "spam" 
    ... 
    >>> callable(Spam2().do_spam)  # True 
    

它们都是可调用的,因为它们定义了一个 __call__特殊的方法。这是使对象可调用的唯一方法。

至于静态方法和类方法,虽然它们通常包装可调用对象(然后通过描述符协议(protocol)公开),但它们本身不可调用,因为它们没有定义 __call__。特殊方法。