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__)
,它返回A 模块类型。模块的语义详细介绍: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))
这意味着您可以用模块的 name 来调用(实例化(模块作为必需的参数,将DOCSTRING作为可选参数。
让我们遍历一些示例:
>>> type(int)
<class 'type'>
所以,由于type(int)
返回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
所以,将东西放在一起:
-
int
是类型type
的对象 -
int()
是类型int
的(整数(对象
另一个示例:
>>> type(str())
<class 'str'>
这意味着
>>> (type(str())() == '') and (type(str())() is '')
True
因此,它的行为就像字符串对象:
>>> type(str())().join(['Hello', ', World!'])
'Hello, World!'
我感觉我可能使这看起来比实际的要复杂得多……
不是! type()
返回对象的类。所以:
-
type(12)
只是写作int
的丑陋方式 -
type(12)(12)
只是写作int(12)
的丑陋方式
所以,"是!",type()
返回可可。但最好将其视为(来自官方文档(
类
使用一个参数,返回对象的类型。返回值是类型对象,通常与对象返回的对象。__类__。