Python type() 函数 returns 可调用

Python type() function returns a callable

type(object) returns 对象类型。

>>> 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__) 应该 return 以 ('my_module') 作为参数的可调用对象。 type(object) returns 可调用对象?

如何理解这是做什么的?

对象的type()函数returnsclass。在 type(__builtins__) 的情况下,它 returns 一个 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))

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

让我们运行通过一些例子:


>>> type(int)
<class 'type'>

所以,既然type(int) returns一个type,那么

是有道理的
>>> type(int)(12)
<class 'int'>

因为

>>> type(12)
<class 'int'>

更重要的是:

>>> (type(int)(12) == type(12)) and (type(int)(12) is type(12))
True

现在,如果您改为:

>>> type(int())
<class 'int'>

这也是预期的,因为

>>> (int() == 0) and (int() is 0)
True

>>> (type(int()) = type(0)) and (type(int()) is type(0))
True

所以,把事情放在一起:

  • inttype
  • 类型的对象
  • int()int
  • 类型的(整数)对象

另一个例子:

>>> type(str())
<class 'str'>

这意味着

>>> (type(str())() == '') and (type(str())() is '')
True

因此,它的行为就像一个字符串对象:

>>> type(str())().join(['Hello', ', World!'])
'Hello, World!'

我觉得我可能让这看起来比实际情况复杂得多......事实并非如此!


type() returns 对象的 class。所以:

  • type(12) 只是一种丑陋的写法 int
  • type(12)(12) 只是一种丑陋的写法 int(12)

因此,"Yes!"、type() returns 可调用。但最好将其视为(来自 official docs

class type(object)

With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.