可调用模块 [英] Callable modules
问题描述
为什么Python不允许模块具有 __call__
一个>方法? (显然,直接导入并不容易.)特别是,为什么不使用a(b)
语法找到__call__
属性,就像对函数,类和对象一样? (对于模块而言,查找是否完全不兼容?)
Why doesn't Python allow modules to have a __call__
method? (Beyond the obvious that it wouldn't be easy to import directly.) Specifically, why doesn't using a(b)
syntax find the __call__
attribute like it does for functions, classes, and objects? (Is lookup just incompatibly different for modules?)
>>> print(open("mod_call.py").read())
def __call__():
return 42
>>> import mod_call
>>> mod_call()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> mod_call.__call__()
42
推荐答案
只有在对类型而不是在实例上定义特殊方法时,才保证隐式调用它们. (__call__
是模块实例mod_call
的属性,而不是<type 'module'>
的属性.)您不能向内置类型添加方法.
Special methods are only guaranteed to be called implicitly when they are defined on the type, not on the instance. (__call__
is an attribute of the module instance mod_call
, not of <type 'module'>
.) You can't add methods to built-in types.
https://docs.python.org/reference/datamodel.html #special-lookup
这篇关于可调用模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!