← 中文资源

简体中文版本

__call__ 让实例可调用

定义 __call__ 之后实例就能像函数一样被调用:Multiplier 直接传值即乘,LastLetter 塞进 sorted 的 key 槽位,callable() 报告的是能力而不是类型。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

20 30
['banana', 'fig', 'cherry']
True True

实现说明

call 让实例可调用以类 Multiplier、LastLetter和函数 __init__、__call__为骨架。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 __init__、__call__。

入口签名:def __init__(self, factor)

核心语句

def __init__(self, factor):
    self.factor = factor
def __call__(self, value):
    return value * self.factor
def __call__(self, word):
    return word[-1]

代码示例

class Multiplier:
    def __init__(self, factor):
        self.factor = factor

    # __call__ lets instances be invoked like functions
    def __call__(self, value):
        return value * self.factor

double = Multiplier(2)
triple = Multiplier(3)
print(double(10), triple(10))

class LastLetter:
    def __call__(self, word):
        return word[-1]

# Callable instances drop into any function-shaped slot, like sort keys
words = ["banana", "fig", "cherry"]
print(sorted(words, key=LastLetter()))

# callable() reports the capability, not the type
print(callable(double), callable(Multiplier))