1.函数的创建
ef say_hi():
print('hello')
print('欢迎来到大熊课堂')
#调用函数
say_hi()
2.函数参数的传递
#普通参数
def say_hi(name):
print(f'hello, {name}')
print('欢迎来到大熊课堂')
say_hi('andy')
def create_window(width,height):
print(f'窗户的宽是{width}, 高是{height}')
create_window(1,2)
#默认参数 如果传递参数的时候不添,就会使用默认值
def total(hour, salary=8):
print(f'薪水为{hour*salary}元')
total(8)#薪水默认8元
total(8,10)
#关键字参数
def student(firstname, lastname):
print(f'firstname is {firstname}, lastname is {lastname}')
student(lastname='Feng', firstname='andy')
#通过这种形式,顺序就不重要了
#不定长参数
def my_function(*args, **kwargs):#*为元组形式, **为字典形式
print(kwargs)
print(args)
for i in args:
print(i, end=' ')
print('\n')
for key, value in kwargs.items():
print(f'{key}->{value}')
my_function('hello', 'welcome', 'to', 'daxiong', lastname='Feng', firstname='andy')
输出:
3.函数返回值
#求圆的面积
pi = 3.14
def area(r):
return pi*(r**2)
print(area(2))
def transform_minute(minutes):
hour = minutes // 60
minute = minutes % 60
return hour, minute
h, m = transform_minute(200)
print(f'hours is {h}, minutes is {m}')
输出:
4.函数的全局变量与局部变量
a = 1#全局变量
l = [1,2,3]
def t1():
a = 100
print(a)#在函数中局部变量优先,首先查找局部变量,再查找全局变量
def t2():
a = 200#局部变量
print(a)
def t3():
global a
a = 300#局部变量
print(a)
def t4():
l.append(5)
print(l)#这里相当于对c语言中的数组进行修改,因为l是可变类型,可以对其进行修改
#a += 1 这里是错的,a全局变量是不可变类型,无法修改
t1()
t2()
t3()
t4()
print(a)
输出:
5.匿名函数
用于当函数代码只有一行时执行,来减少代码模块
lambda 参数:表达式
def add(x,y):
return x+y
result = add(1,2)
print(result)
e = lambda x,y:x+y #这里的lambda用于实现与add相同的功能
print(e(1,2))
r = (lambda x,y:x+y)(1,2)#传递参数时要添加括号再传递
print(r)
#lambda用于表达一个东西,没有返回结果
lambda应用:
result = [x**2 for x in range(10)]
print(result)
'''
def multiple(x)
return x**2
(lambda x:x**2)(x)相当于multiple(x),因为要传递参数
所以要加括号(x)
'''
print([(lambda x:x**2)(x) for x in range(10)])
list_val = [(5,6),(7,3),(1,8)]
list_val.sort(key=(lambda x:x[1]))
print(list_val)
#lambda x:x[1]实现函数名的功能
'''
def take_second(list_val)
return list_val[1]
相当于key = take_second
'''
6.函数式编程:
# def doubler(l):
# for item in range(0, len(l)):
# l[item] *= 2
# return l
#
# list_val = [1,2,3,4,5]
# print(doubler(list_val))
# print(doubler(list_val))第二次输出与上一次不一样
#函数式编程:每次相同的输入都会得到相同的输出
def doubler(l):
new_list = []
for item in l:
new_list.append(item*2)
return new_list
list_val = [1,2,3,4,5]
print(doubler(list_val))
print(doubler(list_val))
7.函数内部还可以创建函数
def test1():
a = 10
print('test1开始执行')
print(f'test1内部变量a的值是{a}')
def test2():
nonlocal a#这里为修改test2外面的a的值
a = 100
print('test2开始执行')#在函数内部定义的函数只能在函数内部调用
print(f'test2内部变量a的值是{a}')
test2()
print(f'test1内部变量a的值是{a}')
test1()
输出:
8.三个函数:
map函数:
def doubler(x):
x *= 2
return x
list_val = [1,2,3,4,5]
#result = map(doubler, list_val)
result = map(lambda x:x*2, list_val)
print(list(result))
#map(函数名,列表)将列表中的每一个值都用函数来处理,返回的是一个迭代器
print([i*2 for i in list_val])
filter函数:
def is_odd(x):
# if x % 2 == 1:
# return True
# else:
# return False
return x % 2 == 1
list_val = [1,2,3,4,5]
#result = filter(is_odd, list_val)
result = filter(lambda x:x%2==1, list_val)
print(list(result))
#filter(表达式,列表)是过滤掉不符合表达式内容的列表中的值
reduce函数:
from functools import reduce
def add(x, y):
return x+y
list_value = [1,2,3,4,5]
#result = reduce(add,list_value)
result = reduce(lambda x,y:x+y,list_value)
print(result)
#reduce用于求和,最终生成一个求和的结果.需要从functools导入
结果输出为:15
9.函数的用途:
#赋值
def func(message):
print(f'Got a message:{message}')
send_message = func
print(func)
send_message('hello,world!')
#作为参数
def get_message(message):
return f'Got a message:{message}'
def call(func,message):
print(func(message))
call(get_message, 'hello world!')
#支持嵌套
def func(message):
def get_message(message):
print(f'Got a message:{message}')
return get_message(message)
func('hello wordl!')
#返回值
def func():
def get_message(message):
return f'Got a message:{message}'
return get_message
send_message = func()
print(send_message('hello world'))
10.函数装饰器:
import time
def decorator(func):
def wrapper(number):
print('wrapper starts!')
start_time = time.perf_counter()
func(number)
end_time = time.perf_counter()
print(f'函数运行时间:{end_time-start_time}')
print('wrapper ends!')
return wrapper
def for_loop(number):
print('for_loop starts!')
for i in range(number):
pass
print('for_loop ends!')
def while_loop(number):
print('while_loop starts!')
i = 0
while i < number:
i += 1
print('while_loop ends!')
new_for = decorator(for_loop)
new_for(10000)
new_while = decorator(while_loop)
new_while(10000)
输出:
不用函数装饰器的时候,每次要使用decorator函数就要把被调用函数的函数名传递进去,然后赋值给一个变量,最后再调用这个变量。
使用函数装饰器:
import time
def decorator(func):
def wrapper(number):
print('wrapper starts!')
start_time = time.perf_counter()
func(number)
end_time = time.perf_counter()
print(f'函数运行时间:{end_time-start_time}')
print('wrapper ends!')
return wrapper
@decorator#使用decorator装饰器
def for_loop(number):
print('for_loop starts!')
for i in range(number):
pass
print('for_loop ends!')
@decorator
def while_loop(number):
print('while_loop starts!')
i = 0
while i < number:
i += 1
print('while_loop ends!')
for_loop(10000)
while_loop(10000)
#函数装饰器是指通过装饰器来修改原来的一些功能,使原来的函数不需要修改
输出:
这里使用函数装饰器之后就不用再进行函数的赋值,直接调用要执行的函数即可
11.函数装饰器传递不定长参数
import time
import functools
def decorator(func):
@functools.wraps(func)#保存被装饰函数的元信息,若不写这个则print(welcome.__name__)输出的是wrapper,元信息被修改
def wrapper(*args, **kwargs):
print('wrapper starts!')
start_time = time.perf_counter()
func(*args, **kwargs)
end_time = time.perf_counter()
print(f'函数运行时间:{end_time-start_time}')
print('wrapper ends!')
return wrapper
@decorator
def welcome(*args, **kwargs):
name, gender = args
gender = '先生' if gender == '男' else '女士'
print(f'hi {name}{gender}, welcome!')
print(f"{name} 的年龄是{kwargs['age']}, 爱好是{kwargs['hobby']}")
welcome('andy', '男', age = '18', hobby = 'basketball')
print(welcome.__name__)
输出:
11.函数装饰器的嵌套
import functools
def decorator1(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('执行装饰器1')
func(*args, **kwargs)
return wrapper
def decorator2(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('执行装饰器2')
func(*args, **kwargs)
return wrapper
@decorator1
@decorator2
def welcome(message):
print(message)
#等价于new_welcome = decorator1(decorator2(message))
#new_welcome('welcome to the course!')
welcome('welcome to the course!')
输出: