7.10 函数对象

函数是第一类对象:函数名指向的值可以被当做参数传递

在python中,所有变量存放的值只要是地址,我们就称之为对象。

  ——所有变量都是用来存放地址的,所以都是对象

  ——存放整型的地址就是整型对象,存放函数的地址就是函数对象,

    存放文件的地址就是文件对象

函数对象:存放函数地址的变量就是函数对象

def func():      # 这里的func就是函数对象
    pass

1.函数名可以被传递

name = 'bitten'
x = name
print(x)  # bitten
print(id(x))  # 4537026352
def func():
    print('from func')
print(id(func))  # 4536540696

f = func  # 函数名可以传递,下面f就等价于func

print(func)  # <function func at 0x10154ae18>
func()  # from func
print(f)  # <function func at 0x10e974e18> 
      # 其实指向的也是函数func指向函数体代码的内存地址
f() # from func

2.函数名可以被当做参数传递给其他函数

def func():
    print('from func')

def index(args):
    print(args)  # <function func at 0x101b80e18>
    args()  # from func
    print('from index')  # from index
index(func)

3. 函数名可以被当做函数的返回值

def index():
    print('index')

def func():
    print('func')
    return index
res = func()  # func
print(res)  # <function index at 0x108027e18>
res()  # index

4. 函数名可以被当做容器类型的参数

def register():
    username = input()
    pwd = input()
def login():
    print('login...')

msg ='''
1.注册
2.登录
'''
func_dict = {
    '1':register,
    '2':login,

}
while True:
    print(msg)
    choice = input('请选择要执行的功能>>>:').strip()  # 去空格
    if choice in func_dict:
        func_dict.get(choice)()
    else:
        print('没有该功能')

猜你喜欢

转载自www.cnblogs.com/PowerTips/p/11165765.html