CPython中函数的非本地变量

函数对象的特殊属性

NOTE 当前测试的CPython解释器版本为

1
2
3
>>> print(__import__('sys').version)
3.7.3 (default, Mar 27 2019, 16:54:48)
[Clang 4.0.1 (tags/RELEASE_401/final)]

以当前版本的解释器下执行下面的代码,可得到一个Markdown表格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def outer(freevar=None):
def inner(a, b: int=1, *args, c: str='1', **kwds) -> tuple:
'a test function'
return freevar, a, b, args, c, kwds
return inner

fn = outer()

print('attribute', 'type', 'setable', 'reason', sep=' | ')
print(*'-'*4, sep=' | ')
for attr in dir(fn):
try:
obj = getattr(fn, attr)
setattr(fn, attr, obj)
print('`%s`'%attr, type(obj), True, '', sep=' | ')
except Exception as exc:
print('`%s`'%attr, type(obj), False, '`%s`'%exc, sep=' | ')
attribute type setable reason
__annotations__ <class ‘dict’> True
__call__ <class ‘method-wrapper’> True
__class__ <class ‘type’> False __class__ assignment only supported for heap types or ModuleType subclasses
__closure__ <class ‘tuple’> False readonly attribute
__code__ <class ‘code’> True
__defaults__ <class ‘tuple’> True
__delattr__ <class ‘method-wrapper’> True
__dict__ <class ‘dict’> True
__dir__ <class ‘builtin_function_or_method’> True
__doc__ <class ‘str’> True
__eq__ <class ‘method-wrapper’> True
__format__ <class ‘builtin_function_or_method’> True
__ge__ <class ‘method-wrapper’> True
__get__ <class ‘method-wrapper’> True
__getattribute__ <class ‘method-wrapper’> True
__globals__ <class ‘dict’> False readonly attribute
__gt__ <class ‘method-wrapper’> True
__hash__ <class ‘method-wrapper’> True
__init__ <class ‘method-wrapper’> True
__init_subclass__ <class ‘builtin_function_or_method’> True
__kwdefaults__ <class ‘dict’> True
__le__ <class ‘method-wrapper’> True
__lt__ <class ‘method-wrapper’> True
__module__ <class ‘str’> True
__name__ <class ‘str’> True
__ne__ <class ‘method-wrapper’> True
__new__ <class ‘builtin_function_or_method’> True
__qualname__ <class ‘str’> True
__reduce__ <class ‘builtin_function_or_method’> True
__reduce_ex__ <class ‘builtin_function_or_method’> True
__repr__ <class ‘method-wrapper’> True
__setattr__ <class ‘method-wrapper’> True
__sizeof__ <class ‘builtin_function_or_method’> True
__str__ <class ‘method-wrapper’> True
__subclasshook__ <class ‘builtin_function_or_method’> True
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×