Python函数对象类型

时间:2018-01-13 18:50:42

标签: python python-3.x function object

如果我这样做:

def foo():
     pass

type(foo)

我明白了:

<class 'function'>

然后当我这样做时:

print(function.__dict__)

我明白了:

NameError: name 'function' is not defined

但如果我这样做:

print(str.__dict__)

我得到了班级__dict__的{​​{1}}。

为什么我可以访问班级str的{​​{1}}但无法访问班级__dict__的{​​{1}}?

1 个答案:

答案 0 :(得分:4)

因为function类型不可用作built-in

Python核心引擎定义了大量的对象定义,不需要混乱到处都可用的命名空间。无论如何,你通常不会直接使用该对象。在任何地方(或通过builtins module)可用的对象列表都经过精心策划,只包含编写Python代码时经常需要的内容。

你仍然可以访问type()所见的类型,所以请使用:

>>> type(foo)
<class 'function'>
>>> type(foo).__dict__
mappingproxy({'__repr__': <slot wrapper '__repr__' of 'function' objects>, '__call__': <slot wrapper '__call__' of 'function' objects>, '__get__': <slot wrapper '__get__' of 'function' objects>, '__new__': <built-in method __new__ of type object at 0x102e5f030>, '__closure__': <member '__closure__' of 'function' objects>, '__doc__': <member '__doc__' of 'function' objects>, '__globals__': <member '__globals__' of 'function' objects>, '__module__': <member '__module__' of 'function' objects>, '__code__': <attribute '__code__' of 'function' objects>, '__defaults__': <attribute '__defaults__' of 'function' objects>, '__kwdefaults__': <attribute '__kwdefaults__' of 'function' objects>, '__annotations__': <attribute '__annotations__' of 'function' objects>, '__dict__': <attribute '__dict__' of 'function' objects>, '__name__': <attribute '__name__' of 'function' objects>, '__qualname__': <attribute '__qualname__' of 'function' objects>})

您也可以通过types模块访问types.FunctionType name

>>> types.FunctionType
<class 'function'>