本章主要介绍Python的函数定义和lambda表达式、以及变量作用域和方法的参数定义
学完本章:
你将会定义函数和lambda有一定了解
变量的作用域
1、方法和函数区别
- python 语言上看
- 方法是站在OOP思想上,跟对象是绑定在一起,对象具有某种行为
- 函数是站在复用的思维,为了复用代码块, 方法可以作为函数一种实现
1.1、比如list的方法
lst = [1,2,3,4,5]
"""
lst 中存在 一些方法
1. append
2. count
3. extend
4. insert
5. pop
6. remove
7. reverse
8. sort
"""
# append 追加元素 : [1,2,3,4,5,6]
lst.append(6)
# count计数, 表示 list 存在2的个数有多少: 1个
lst.count(2)
# 查看帮助
help(lst)
2、函数
2.1、定义函数
- 语法
- 参数:可选
- return语句: 可选
def 函数名(参数)
逻辑
return 返回值
- 定义函数示例,猜猜那个门有奖品
# 猜那个门有奖品
mylist = [' ', '0', ' ']
from random import shuffle
def shuffle_list(mylist):
shuffle(mylist)
return mylist
def player_guess():
guess = ''
while guess not in ['0','1','2']:
guess = input("Pick a number: 0, 1, or 2: ")
return int(guess)
def check_guess(mylist, guess):
if mylist[guess] == '0':
print('Correct Guess!')
else:
print('Wrong! Better luck next time')
print(mylist)
def guess():
mylist = [' ', '0', ' ']
mixedup_list = shuffle_list(mylist)
guess = player_guess()
check_guess(mixedup_list, guess)
# 猜数字
guess()
3、Lambda 表达式
-
简化定义函数步骤,是一种语法糖,特别只是一次用到简单的函数,可以定义成Lambda
-
语法
-
lambda 参数: 表达式 (参数可以多个)
-
map 它会迭代每个元素,将元素转换其他形式,无论加减乘除,也就说每个元素都会经过某个函数
# 例如:定义一个平方函数,我们然后数字元素都经过平方运算,得到新值 [1, 4, 9, 16, 25]
def square(num):
return num**2
my_nums = [1,2,3,4,5]
a = list(map(square, my_nums))
print(a)
# 第二例子: 如果字符是偶数就是显示'even', 如果奇数就返回字符串第一个元素
def splicer(mystring):
if len(mystring) % 2 ==0:
return 'even'
else:
return mystring[0]
mynames = ['John', 'Cindy', 'Sarah', 'Kelly', 'Mike']
st = list(map(splicer, mynames))
print(st)
# 2. filter 函数
# 过滤满足条件为true元素
# 过滤偶数数据
def check_even(num):
return num % 2 == 0
nums = [0,1,2,3,4,5,6,7,8,9,10]
f = list(filter(check_even, nums))
print(f)
# 3. lambda表达式
# 匿名函数,可以省略def 关键字, 同时 lambda 表达式是一条语句,不是语句块
# 我们一步一步进化函数, 例如求数字的平方
def square(num):
result = num**2
return result
# 去掉 result变量
def square(num):
return num**2
# 写成一行
def square(num): return num**2
# lambda表达式
square = lambda num: num ** 2
print(square(2))
# 改一下上面map 平方计算
list(map(lambda num: num ** 2, my_nums))
# 改一下上面的filter,过滤偶数
list(filter(lambda n: n % 2 == 0, nums))
# 定义 取出字符串第一个元素
first = lambda s: s[0]
print(first("A2223"))
# 反转字符串
revsered = lambda s: s[::-1]
print(revsered("A2223"))
# 定义加法
plus = lambda x, y : x + y
print(plus('111', '1212112'))
4、内置语句和作用域
- 全局变量不会被本地改变, 除非使用global 关键字
- 对于语句作用范围,可以简单用LEGB字母描述
- LEGB 规则
- L: 本地变量,赋值 定义在def 或 lambda中
- E: 封闭的函数本地变量,从内部到外部
- G: 全局变量
- B: 内嵌变量,例如open,range,不可改变
# 1、Local
f = lambda x: x**2
# 2. Enclosing function locals : Hello Sammy
name = 'This is a global name'
def greet():
# 内嵌函数
name = 'Sammy'
def hello():
print('Hello ' + name)
hello()
greet()
# 3. Global 全局变量 : 'This is a global name'
print(name)
# 4. 内嵌
len
# 函数内部赋值不能影响global
"""
结果
x is 50
Changed local x to 2
x is still 50
"""
x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still ', x)
# 可以在函数内部声明变量为global 那么值就可以修改了
"""
Before calling func(), x is: 50
This function is now using the global x!
Because of global x is: 50
Ran func(), changed global x to 2
Value of x (outside of func()) is: 2
"""
x = 50
def func():
global x
print('This function is now using the global x!')
print('Because of global x is :', x)
x = 2
print('Ran func(), changed global x to', x)
print('Before calling func(), x is ', x)
func()
print('Value of x (outside of func()) is: ', x)
5、参数(args和kwargs)
- 定义list的可变参数:星号变量名(*变量名)
- 定义dictionary的可变参数:星号星号变量名(**变量名)
- 两个可变参数可以混合使用
# 可变参数 *args 和 **kwargs
# *args 表示list列表, **kwargs 表示key-value 可变参数
# 元组(tuple) sum 初始例子,转入两个参数,然后乘以5%
def myfunc(a,b):
return sum((a,b))*.05
myfunc(40,60)
# 为了支持多个参数,定义 key 对应默认值,这个其实也不是可变的
def myfunc(a =0, b =0, c=0, d=0, e=0):
return sum((a,b,c,d,e))*.05
myfunc(40,60,20)
# 利用 *args实现可变,实际*args表示tuple(元组): 6.0
def myfunc(*args):
return sum(args)*.05
myfunc(40,60,20)
# 这里'args'只是名称,它不定要是'args',也可以命名其他变量
def myfunc(*spam):
return sum(spam)*.05
myfunc(40, 60, 20)
# **kwargs 这个利用 dictionary作为可变参数,key-value, 传入一个map
def myfunc(**kwargs):
if 'fruit' in kwargs:
print(f"My favorite fruit is {kwargs['fruit']}")
else:
print("I don't like fruit")
# My favorite fruit is pineapple
myfunc(fruit='pineapple')
# I don't like fruit
myfunc()
# *args 和 **kwargs混合使用
def myfunc(*args, **kwargs):
if 'fruit' and 'juice' in kwargs:
print(f"I like {' and '.join(args)} and my favorite fruit is {kwargs['fruit']}" )
print(f"May I have some {kwargs['juice']} juice?")
else:
pass
# I like eggs and spam and my favorite fruit is cherries
# May I have some orange juice?
myfunc('eggs', 'spam', fruit='cherries', juice='orange')
# 顺序不能弄反, 会报错
#myfunc(fruit='cherries', juice='orange', 'eggs', 'spam')
总结
- 学习定义函数语法(def关键字, def 函数名(参数): 逻辑)
- 学习定义简单的lambda表达式(lambda 参数 : 表达式)
- 学习可变参数*变量名表示list可变参数,**变量名表示dictionary的可变参数
- 学习变量的作用域,LEGB(Local, Enclosing, Global, emBedded)
参考文档
- https://github.com/Pierian-Data/Complete-Python-3-Bootcamp.git