您创建的类没有什么特别之处(它甚至不是ModuleType子类),所以它的方法没有什么特别之处__call__。如果你想用参数调用它,只需在__call__定义中添加参数:
import sys
class foo(object):
def __call__(self, x):
return f'callable, and called with {x}'
sys.modules[__name__] = foo()
现在,您可以将参数传递给它,就像任何其他可调用对象一样:
import foo
print(foo('hello'))
输出是:
callable, and called with hello
从评论中,您尝试这样做:
def __call__(a, self):
return a
但是,就像 Python 中的所有方法一样,它__call__想要排self在第一位。它不关心名称(除非你用关键字参数调用它),只关心顺序:第一个参数获取接收者(fooin foo('hello')),即使你调用了那个参数a,第二个参数获取第一个普通参数(the 'hello'),即使你调用了那个参数self。
因此,您将模块foo作为第一个参数传递a,而 youreturn a则返回foo.
这就是你得到这个的原因:
<sta.foo object at 0x10faee6a0>
这不是错误,这是当您打印出未定义__repr__或的类的实例时得到的完全有效的输出__str__。