__call__ 可以在 Python 中返回一些东西吗?

The*_*Phi 0 python

我试图用这样的代码来理解一些程序:

class foo(object):
    def __init__(self):
        # some initializations 
        pass

    def __call__(self, a, b):
        return a+b

x = foo()
x(2, 3)
Run Code Online (Sandbox Code Playgroud)

返回调用是否在__call__错误中?它不会引发任何错误,但是我们如何访问返回值__call__呢?

Lin*_*ios 5

是的,您绝对可以从 返回一个值__call__,该值将用作调用本身的返回值。

使用您的示例:

class foo(object):
    def __init__(self):
        # some initializations 
        pass

    def __call__(self, a, b):
        return a+b

obj = foo()
print obj(1, 2) # Prints `3`
Run Code Online (Sandbox Code Playgroud)