首页 > 其他 > 详细

函数对象

时间:2019-11-11 15:04:18      阅读:77      评论:0      收藏:0      [点我收藏+]

函数是第一类对象

1、函数名可以被引用

# 1、函数名可以被引用
def add(x, y):
    print(x + y)


a = add
a()

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

# 2、函数名可以当作参数传递
def add(x, y):
    print(x + y)


def index(x, y, operation):
    operation(x, y)


index(1, 2, add)

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

 

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

def index():
    print(hello index)


def func(a):
    return a


f = func(index)
f()

4、函数名可以作为容器类型的元素 

1、控制台---简单菜单选项

技术分享图片
def login():
    print(Login in!)


def register():
    print(register)


def shopping():
    print(shopping)


def pay():
    print(pay)


func_dict = {
    1: login,
    2: register,
    3: shopping,
    4: pay,
}

while True:
    print("""
1、登录
2、注册
3、购物
4、结账
""", end=‘‘)
    choice = input(>>>).strip()
    if choice == 5:
        break
    if choice not in func_dict:
        continue
    func_dict[choice]()
View Code

2、基于字典索引的简单计算机

技术分享图片
# 基于字典索引的简易计算器
def add(x, y):
    return x + y


def multiply(x, y):
    return x * y


def divide(x, y):
    return x / y


my_dict = {+: add, /: divide, *: multiply}

while True:
    raw_str = input(>>>)
    new_str = ‘‘
    for char in raw_str:
        if char !=  :
            new_str += char
    if new_str.find(/) != -1:
        operation_index = new_str.find(/)
    elif new_str.find(*) != -1:
        operation_index = new_str.find(*)
    elif new_str.find(+) != -1:
        operation_index = new_str.find(+)
    operation = new_str[operation_index]
    first_num = float(new_str[:operation_index])
    second_num = float(new_str[operation_index + 1:])
    result = 0
    result = my_dict[operation](first_num, second_num)
    print(result)
View Code

 

 

 

 

函数对象

原文:https://www.cnblogs.com/Ghostant/p/11834709.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!