函数是一等对象公民的常见用法

8次阅读

共计 748 个字符,预计需要花费 2 分钟才能阅读完成。

什么是一等函数

> 一等对象定义为满足下述条件的程序实体:
>
>- 在运行时创建
>- 能赋值给变量或数据结构中的元素
>- 能作为参数传给函数
>- 能作为函数的返回结果

所以在 python函数 int str等都是一等公民


一等函数的常用应用

  • 检查函数是否可调用
  • 查看函数所具有的属性(函数内省)


  1. 函数可调用对象 callable() 函数

    ​如果想判断函数能否被调用,可以使用内置的 callable() 函数

    def foo():
        return 'Hello'
    bool_result=callable(foo)

    ​运行代码,bool_result的值为True

  2. 函数内省

    使用 dir 函数可以探知函数所具有的属性

    dir(foo)

    运行输出 foo 所具有的属性如下:

    ['__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__']

正文完
 0