python函数
1、定义函数

>>> def add(x,y):
r = x + y
return r
>>> add(2,3)
5
>>> add('abc','def')
'abcdef'
>>> c = add(2,3)
>>> c
5
'''
'Python' --> 'pYTHON'
'''
def convert(s):
lst = [i.upper() if i==i.lower() else i.lower() for i in s]
return "".join(lst)
s = 'Hello'
c = convert(s)
print(c)
2、调用函数
• 按照位置提供参数
>>> add(2,3)
• 指明参数名称
>>> add(x=2,y=3)
• 设置参数的默认值
有默认值时需要把默认值参数放在后面,否则报错
>>> def bar(x,y=3):
print('x=',x)
print('y=',y)
>>> bar(2)
x= 2
y= 3
>>> bar(2,5)
x= 2
y= 5
>>> def bar(x=3,y):
SyntaxError: non-default argument follows default argument
3、返回值
• 返回一个值
• 返回多个值
return语句的作用:中断当前函数,并且跳出函数体,然后把值返回到函数调用处
>>> def my_fun():
return 1,2,3
>>> r = my_fun()
>>> r
(1, 2, 3)
>>> a,b,c = my_fun()
>>> a
1
>>> b
2
>>> c
3
4、参数收集
• 一个*的作用
把其余的参数收集到一个元组中,在这种情况下,需要使用名称来指定后续参数,不然的话会报错
>>> def fun(x,*args):
print("x=",x)
print("args=",args)
>>> fun(1,2,3,4,5)
x= 1
args= (2, 3, 4, 5)
>>> fun(1)
x= 1
args= ()
>>> fun()
Traceback (most recent call last):
File "<pyshell#139>", line 1, in <module>
fun()
TypeError: fun() missing 1 required positional argument: 'x'
• 两个**的作用
收集关键字参数,这样得到的是一个字典而不是元组
>>> def bar(x,**kwargs):
print('x=',x)
print('kwargs=',kwargs)
>>> bar(1,a=2,b=3,c=4)
x= 1
kwargs= {'a': 2, 'b': 3, 'c': 4}
>>> def foo(*args,**kwargs):
print(args)
print(kwargs)
>>> foo(1,2,3,a=9,b=8,c=7)
(1, 2, 3)
{'a': 9, 'b': 8, 'c': 7}
'''
假设有数据:d = {‘a’: 39, ‘b’:40, ‘c’:9, ‘d’:10}(字典的键值对还可
以增加),编写函数,实现对这个字典中键值对的查询。例如向
函数提供如a=1, b=40等参数,查询这些是否为此数据的值。
'''
def findkv(dct, **kwargs):
r = {k:v for k, v in kwargs.items() if dct.get(k)==v}
return r
d = {'a':39, 'b':40, 'c':99, 'd':100}
fr = findkv(d, a=1, b=40)
print(fr)
5、嵌套函数和装饰器
• 嵌套函数
>>> def foo(a):
a.append(99)
return a
>>> lst = [1,2,3]
>>> lst.append(0)
>>> lst
[1, 2, 3, 0]
>>> foo(lst)
[1, 2, 3, 0, 99]
>>> lst
[1, 2, 3, 0, 99]
函数也是对象,再内存中有地址,定义函数时,其参数可以引用任何对象,也就可以引用其他的函数
>>> foo
<function foo at 0x00000181FD3E6EE0>
>>> def bar():
print('I am bar')
>>> def foo(f):
f()
>>> foo(bar)
I am bar
函数的作用域问题
>>> def foo1():
def bar2():
print("I am bar2")
return bar2
>>> b = foo1()
>>> b()
I am bar2
>>> bar2()
Traceback (most recent call last):
File "<pyshell#195>", line 1, in <module>
bar2()
NameError: name 'bar2' is not defined
>>> b
<function foo1.<locals>.bar2 at 0x00000181FD3E8790>
局部变量和全局变量
函数里面的变量是局部变量,可以用global申明使用全局变量
>>> a=1
>>> def f3():
a = a + 1
print(a)
>>> f3()
Traceback (most recent call last):
File "<pyshell#210>", line 1, in <module>
f3()
File "<pyshell#209>", line 2, in f3
a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment
>>> def f3():
global a
a = a + 1
print(a)
>>> f3()
2
作用域问题在嵌套函数中同样存在,也可以用nonlocal申明变量不是局部的
>>> def foo():
a = 1
def bar():
nonlocal a
a = a + 1
print(a)
bar()
>>> foo()
2
'''
G = mg, g=9.8
'''
def w(m, g):
return m * g
def weight(g):
def cal_mg(m):
return m * g
return cal_mg
w = weight(10) # g = 10
G = w(100)
G2 = w(50)
print(G)
w2 = weight(9.78046)
G3 = w2(100)
print(G3)
• 装饰器
@p_deco是装饰器语句,表示p_deco函数装饰了book函数
def p_deco(func):
def wrapper(name):
return "<p>{0}</p>".format(func(name))
return wrappe
@p_deco
def book(name):
return "the name of my book is {0}".format(name)
# laoqi = p_deco(book)
# py_book = laoqi("Python大学实用教程")
py_book = book("Python大学实用教程")
print(py_book)
执行结果:<p>the name of my book is Python大学实用教程</p>
def p_deco(func):
def wrapper(name):
return "<p>{0}</p>".format(func(name))
return wrapper
def div_deco(func):
def wrapper(name):
return "<div>{0}</div>".format(func(name))
return wrapper
@div_deco
@p_deco
def book(name):
return "the name of my book is {0}".format(name)
# laoqi = p_deco(book)
# py_book = laoqi("Python大学实用教程")
py_book = book("Python大学实用教程")
print(py_book)
执行结果:<div><p>the name of my book is Python大学实用教程</p></div>
'''
编写一个用于测试函数执行时间的装饰器函数
'''
import time
def timing_func(func):
def wrapper():
start = time.time()
func()
stop = time.time()
return stop - start
return wrapper
@timing_func
def test_list_append():
lst = []
for i in range(1000000):
lst.append(i)
@timing_func
def test_list_compre():
[i for i in range(1000000)]
a = test_list_append()
c = test_list_compre()
print("test list append time:", a)
print("test list comprehension time:", c)
print('append/compre =', round(a/c, 3))0
import time
from functools import wraps
def timethis(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time()
print(func.__name__, end - start)
return wrapper
@timethis
def countdown(n):
while n>0:
n -= 1
@timethis
def test_list_append():
lst = []
for i in range(1000000):
lst.append(i)
@timethis
def test_list_compre():
[i for i in range(1000000)]
countdown(1000000)
countdown(100000000)
test_list_append()
test_list_compre()
6、特殊函数
• lambda
匿名函数lambda:是指一类无需定义标识符(函数名)的函数或子程序。
lambda 函数可以接收任意多个参数 (包括可选参数) 并且返回单个表达式的值。
lambda [arg1 [,arg2,.....argn]]:expression
冒号前是参数,可以有多个,用逗号隔开,冒号右边的为表达式(只能为一个)。其实lambda返回值是一个函数的地址,也就是函数对象。
>>> lam = lambda x:x+3
>>> lam
<function <lambda> at 0x00000181FD3E6CA0>
>>> lam(2)
5
• map
Help on class map in module builtins:
class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
>>> m = map(lambda x:x+3, range(10))
>>> m
<map object at 0x00000181FD349190>
>>> list(m)
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> lst1 = [1,2,3,4,5]
>>> lst2 = [6,7,8,9,0]
>>> lst3 = [7,8,9,2,1]
>>> [x+y+z for x,y,z in zip(lst1,lst2,lst3)]
[14, 17, 20, 15, 6]
>>> r = map(lambda x,y,z:x+y+z,lst1,lst2,lst3)
>>> list(r)
[14, 17, 20, 15, 6]
• filter
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
>>> n = range(-5,5)
>>> f = filter(lambda x:x>0,n)
>>> f
<filter object at 0x00000181FD3E1820>
>>> list(f)
[1, 2, 3, 4]
>>> [i for i in n if i > 0]
[1, 2, 3, 4]
本文深入讲解Python函数的定义与使用,包括参数传递、返回值、参数收集等核心概念,并介绍了嵌套函数、装饰器及特殊函数的应用场景。
155

被折叠的 条评论
为什么被折叠?



