实现说明
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))