函数对象

函数是第一类对象

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