Python type() 函数返回一个可调用对象

标签 python types module callable

type(object) 返回对象的类型。

>>> type(__builtins__)
<type 'module'>
>>> name = type(__builtins__)
>>> type(name)
<type 'type'>
>>> name
<type 'module'>

>>> name('my_module')
<module 'my_module' (built-in)>
>>> name('xyz')
<module 'xyz' (built-in)>
>>> 

在这个语法中,

my_module = type(__builtins__)('my_module')

type(__builtins__) 应该返回以 ('my_module') 作为参数的可调用对象。 type(object) 返回可调用对象?

如何理解这是在做什么?

最佳答案

type() 函数返回对象的类。在 type(__builtins__) 的情况下,它返回一个 Module 类型。模块语义详见:https://docs.python.org/3/library/stdtypes.html#modules

CPython 的源代码在 Objects/moduleobject.c::module_init() 中有:

static char *kwlist[] = {"name", "doc", NULL};
PyObject *dict, *name = Py_None, *doc = Py_None;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__",
                                 kwlist, &name, &doc))

这意味着您可以调用(实例化)模块对象,将模块的名称作为必需参数,并将文档字符串作为可选参数。

关于Python type() 函数返回一个可调用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43771400/

相关文章:

c++ - !expected type-specifier before ‘=’ token

Python 模块分组

Python 库、包、模块

python - 在 PyGTK 中获取要阻止的接口(interface)

python - 套接字服务器 - 获取连接用户的 ip

NumPy vectorize() 或 dot() 出现错误

java - 将整数列表从 Java 传递到 Oracle 函数

c++ - 错误 : No match to call the 'module'

python - 从 sqlite3 远程数据库读取

python - 用相对路径打包数据