函数的小练习
# 输入一个数字,输出与1相加的结果
def add_one(number):
return number + 1
a = add_one(2)#调用函数
print(a)
函数可以作为参数被传递
def say_hello(name):
return f"Hello {name}"
def be_some(name):
return f"Your {name}"
def greet_bob(func):
return func("Bob")
print(greet_bob(say_hello))
print(greet_bob(be_some))
使用装饰器
装饰器: 把一个函数当作参数传递给另一个函数,返回一个替代版的函。
本质上就是一个返回函数的函数。
在不改变原函数的基础上,给函数增加功能。
def say():
print('hello')
def fun():
print('**********')
say()
# 先调用fun()函数,打印出*,然后执行fun函数里的say()函数,打印出hello
fun()
def say():
print('hello')
def hello():
print('!!!!!!!!hello')
def fun(f):
def inner():
print('**********')
f()
print('##########')
return inner
say()#调用say函数,打印出hello
say = fun(say)#调用fun函数,返回inner函数,在inner函数中又调用say函数
# print(say)#所以先打印星,再打印出hello,最后打印出#
say()
hello = fun(hello)
hello()
@语法只是将函数传入装饰器函数
def fun(f):#装饰器
def inner():
print('**********')
f()
print('##########')
return inner
@fun#语法糖
def hello():
print('!!!!!!!hello')
@fun#语法糖
def say():
print('hello')
say()#调用这个函数时,需要在函数前添加语法糖才能调用装饰器
hello()