可调用模块 [英] Callable modules

查看:58
本文介绍了可调用模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆