Loading

python入门之函数对象

函数是第一类对象

First-Class Object :

在 Python 中万物皆为对象,函数也不例外,函数作为对象可以赋值给一个变量、可以作为元素添加到集合对象中、可作为参数值传递给其它函数,还可以当做函数的返回值,这些特性就是第一类对象所特有的。

1、函数名可以被引用

name = 'tank'
dsb = name
 
def index():
    print('from index')
 
 
a = index
a()

2、函数名可以当做参数传递

def foo(x, y, func):
    print(x, y)
    func()
 
 
def bar():
    print('from bar')
 
 
foo(1, 2, bar)

3、函数名可以当做返回值使用

传参的时候没有特殊需求,一定不要加括号,加括号当场执行了

def index():
    print("from index")
 
 
def func(a):
    return a
 
 
a = func(index)
# print(a)
a()
 

4、函数名可以被当做容器类型的元素

def func():
     print('from func')
 
 
 
 
l1 = [1, '2', func, func()]
 
f = l1[2]
 
print(f)
 
def registers():
    print('register')
 
 
def login():
    print('login')
 
 
def shopping():
    print('shopping')
 
 
def pay():
    print('pay')
 
 
choice_dic = {
    '1': registers,
    '2': login,
    '3': shopping,
    '4': pay,
}
 
 
def choice():
    while True:
        print('''
              1 : 注册
              2 :登录
              3 :购物
              4 :付款
              5 :退出''')
        num = input('请输入数字进行选择:').strip()
        if num == '5':
            break
        if num not in choice_dic:
            continue
        else:
            choice_dic[num]()
 
 
choice()
posted @ 2019-11-11 20:57  开花的马铃薯  阅读(245)  评论(0编辑  收藏  举报