函数对象
函数是第一类对象,即函数可以被当做数据处理。
def func():
print('func from')
# 班函数当做对象来用
print(type(func))
print(id(func))
print(func) # func指向一块内存地址,函数名
结果:
<class 'function'>
3107559252992
<function func at 0x000002D388F72400>
func from
一、函数对象的四大功能
1.1 引用
变量名可以被引用,函数名也可被引用
func可以加()调用,那么f也可以加()调用
def func():
print('func from')
a = 1
b = a
print(b) # 变量名
# 变量名可以被引用,函数名也可被引用
f = func # func可以加()调用,那么f也可以加()调用
f()
结果:
1
func from
1.2 可以当容器类型的元素
# 变量名可以放入容器类型数据类型,因此函数也可以
def func():
print('func from')
lt = [1, 2, a, func]
lt[-1]()
结果:
func from
1.3 函数也可以当做函数参数
# 变量名也可以当做函数参数
def f2(name):
name()
f2(func)
结果:
func from
1.4 函数可以当做返回值
# 函数的返回值
def f3(name):
return name
res = f3(func)
print(res)
res()
结果:
<function func at 0x000002222F36C268>
func from
二、函数嵌套
函数内部定义的函数,无法在函数外部使用内部定义的函数。
def f1():
def f2():
print('from f2')
f2()
f2() # NameError: name 'f2' is not defined
def f1():
def f2():
print('from f2')
f2()
f1()
from f2
三、练习
3.1猜年龄游戏
import random
def register():
print('欢迎来到注册页面')
username = input('请输入你的用户名:')
pwd = input('请输入你的密码')
with open('userinfo.txt', 'a', encoding='utf8') as fa:
fa.write(f'{username}:{pwd}|')
def login():
print('欢迎来到登录页面')
username = input('请输入你的用户名:')
pwd = input('请输入你的密码')
with open('userinfo.txt', 'r', encoding='utf8') as fr:
data = fr.read()
data_split = data.split('|') # ['nick:123','tank:123']
userinfo = f'{username}:{pwd}'
if userinfo in data_split:
print('登录成功')
else:
print('登录失败')
def get_price_dict():
"""获取奖品字典"""
with open('price.txt', 'r', encoding='utf8') as f: # price.txt右下角为什么编码,则encoding为什么编码
price_dict = f.read()
price_dict = eval(price_dict) # type:dict # 获取奖品字典
return price_dict
def select_price(price_dict):
"""选择奖品"""
price_self = dict()
# 打印商品
for k, v in price_dict.items():
print(f'奖品编号:{k} {v}')
# 获取奖品的两次循环
for i in range(2):
price_choice = input('请输入你需要的奖品编号:')
if not price_choice.isdigit():
print("恭喜你已经获得一次奖品,奖品为空!并且请输入正确的奖品编号!")
continue
price_choice = int(price_choice)
if price_choice not in price_dict:
print('你想多了吧!')
else:
price_get = price_dict[price_choice]
print(f'恭喜中奖:{price_get}')
if price_self.get(price_get):
price_self[price_get] += 1
else:
price_self[price_get] = 1
print(f'恭喜你获得以下奖品:{price_self}')
def guess_age():
"""猜年龄函数"""
print("欢迎来到猜年龄游戏")
age = random.randint(18, 60) # 随机一个数字,18-60岁
count = 0 # 计数
while count < 3:
count += 1
inp_age = input('请输入你想要猜的年龄:')
# 判断是否为纯数字
if not inp_age.isdigit():
print('搞事就骂你傻逼')
continue
inp_age = int(inp_age)
# 筛选年龄范围
if inp_age > 60 or inp_age < 18:
print('好好题目,18-60岁,非诚勿扰')
continue
# 核心逻辑
if age == inp_age:
print('猜中了,请选择你的奖品')
price_dict = get_price_dict()
select_price(price_dict)
break
elif age > inp_age:
print('猜小了')
elif age < inp_age:
print('猜大了')
continue
msg = '''
1: 登录
2: 注册
3: 猜年龄游戏
'''
func_dic = {
'1': login,
'2': register,
'3': guess_age,
}
print(msg)
choice = input('请选择你需要的功能')
func_dic[choice]()
3.2函数嵌套
比较两个值
def self_max(x, y):
if x > y:
return x
return y
res = self_max(1, 45)
print(res)
res = self_max(self_max(3, 5), self_max(49, 23))
print(res)
结果:
45
49