Python 函数的属性

2020-04-29  本文已影响0人  eeert2

Python的函数也是对象,所以它也具有对象共有的属性:

def fn():
    pass


print(dir(fn))  # ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

除了这些与对象共有的属性之外。函数还具有自己特有的属性:

名称 类型 说明
__annotations__ dict 参数和返回的注解
__call__ method-wrapper 实现()运算符,变成可调用对象
__closure__ tuple 函数闭包,即自由变量的绑定(通常是 None
__code__ code 编译成字节码的函数元数据和函数定义体
__defaults__ tuple 参数的默认值
__get__ method-wrapper 实现只读描述符协议
__globals__ dict 函数所在模块中的全局变量
__kwdefaults__ dict 关键字参数默认值
__name__ str 函数名称
__qualname__ str 函数的限定名称,如 Random.choice
上一篇 下一篇

猜你喜欢

热点阅读