python第一类对象——函数

python中,万事万物为对象,函数也是一个对象。并且函数就是一种第一类对象。

Python中第一类对象的特性:

  1、对象可以赋值给变量

  2、对象可以被当做参数传递

  3、对象可以被当做函数的返回值返回

  4、对象可以作为元素被添加到容器类型中

1、对象可以赋值给变量

函数名作为变量的值传递给该变量时,这个变量所指向的地址跟函数的地址一样。

def func():
    pass

f = func
id(f) = id(func)
f is func = True

2、对象可以被当做参数传递

def func():
    print('func')

def index(func):
    print('index')
    func()

>>> 'index'
>>> 'func'

3、对象可以被当做函数的返回值返回

def func():
    print('func')

def index():
    return func

f = index()
f()

>>> 'func'

4、对象可以作为元素被添加到容器类型中 

def func():
    pass

def index():
    pass

func_list = []
func_list.append(func)
func_list.append(index)
print(func_list)

>>>[<function func at 0x1004931e0>, <function index at 0x100554268>]

5、函数可以嵌套

def outer():
    print('outer')
    def inner():
        print('inner')
    inner()
outer()

>>>'outer'
>>>'inner'

 

    

 

posted @ 2019-07-10 21:23  KbMan  阅读(391)  评论(0编辑  收藏  举报