码迷,mamicode.com
首页 > 编程语言 > 详细

python入门之函数对象

时间:2019-11-11 21:41:43      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:ref   集合   index   else   pytho   register   函数名   rom   退出   

函数是第一类对象

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()

python入门之函数对象

标签:ref   集合   index   else   pytho   register   函数名   rom   退出   

原文地址:https://www.cnblogs.com/cnhyk/p/11838408.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!