可调用类型的定义是什么?

What is the definition of a callable type?

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

在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:

    是"the function call operatation"()的运算符吗?一个也是 可调用类型定义为其实例被函数调用的类型 运算符 () 可以应用于?

  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__() 方法?如果 class 有一个 __call__() 方法,那么它 必须是可调用类型?如果 class 没有 __call__() 方法,那么它可能是也可能不是可调用类型?

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

谢谢。

检查 Callable 的定义

from collections import Callable

源代码如下:

class Callable(metaclass=ABCMeta):

    __slots__ = ()

    @abstractmethod
    def __call__(self, *args, **kwds):
        return False

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Callable:
            if any("__call__" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented

棘手的部分是__subclasshook__的方法,所以任何能找到__call__方法的classes都可以被视为Callable 的子class,而不是直接从它继承。

PS:不仅__subclasshook__可以做到这一点,register()方法还可以将另一个class注册为基[=26的subclass =].

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's or classmethods(接上一题),不要定义__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).

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

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

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

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

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