Python函数对象类型
如果我这样做:Python函数对象类型,python,python-3.x,function,object,Python,Python 3.x,Function,Object,如果我这样做: def foo(): pass type(foo) 我得到: <class 'function'> NameError: name 'function' is not defined 我得到: <class 'function'> NameError: name 'function' is not defined 但如果我这样做: print(str.__dict__) 我得到类str的\uuu dict\uuuu 为什么我可以访问
def foo():
pass
type(foo)
我得到:
<class 'function'>
NameError: name 'function' is not defined
我得到:
<class 'function'>
NameError: name 'function' is not defined
但如果我这样做:
print(str.__dict__)
我得到类str
的\uuu dict\uuuu
为什么我可以访问类
str
的\uuuu dict\uuuu
,但不能访问类函数的\uu dict\uuu
?因为函数类型不能作为
Python核心引擎定义了大量的对象定义,它们不需要把随处可见的名称空间弄得乱七八糟。您通常不会直接使用该对象。处处可用(或通过)的对象列表经过精心策划,只包含编写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>})
因为函数
不是内置名称。