Python--进阶处理7

# ====================第七章:函数=========================

# 为了能让一个函数接受任意数量的位置参数,可以使用一个* 参数
# 为了接受任意数量的关键字参数,使用一个以** 开头的参数
# 一个* 参数只能出现在函数定义中最后一个位置参数后面,而**参数只能出现在最后一个参数。有一点要注意的是,在* 参数后面仍然可以定义其他参数。
def a(x, *args, y):
pass
def b(x, *args, y, **kwargs):
pass

# 希望函数的某些参数强制使用关键字参数传递
# 将强制关键字参数放到某个* 参数或者单个* 后面就能达到这种效果
def recv(maxsize, *, block):
pass

def minmun(*values, clip=None):
pass

# 如果默认参数是一个可修改的容器比如一个列表、集合或者字典,可以使用 None 作为默认值
def spam(a, b=None):
if b is None:
b = []
# 注意:传递一个 None 值和不传值两种情况是有差别的
# 默认参数的值仅仅在函数定义的时候赋值一次
x = 42
def spam(a, b=x):
print(a, b)
spam(1) # 打印出 1,42
x = 23
spam(1) # 还是打印出 1,42
# 默认参数的值应该是不可变的对象,比如 None、True、False、数字或字符串
# 当一些函数很简单,仅仅只是计算一个表达式的值的时候,就可以使用 lambda 表 达式来代替了
add = lambda x, y: x + y
"""
def add(x, y):
return x + y
"""
print(add(2, 3))

# 如果需要减少某个函数的参数个数,你可以使用 functools.partial()
from functools import partial

def spam(a, b, c, d):
print(a, b, c, d)
s1 = partial(spam, 1)
s1(2, 3,4)
s2 = partial(spam, d=42)
s2(1, 2, 3)
s3 = partial(spam, 1, 2, d=42)
s3(3)
# partial() 通常被用来微调其他库函数所使用的回调函数的参数

# 将单方法的类转换为函数--闭包
from urllib.request import urlopen

class UrlTemplate:

def __init__(self, template):
self.template = template

def open(self, **kwargs):
return urlopen(self.template.format_map(kwargs))
# -------------------------------------------------------
def urltemplate(template):
def opener(**kwargs):
return urlopen(template.format_map(kwargs))
return opener
# -------------------------------------------------------

# 带额外状态信息的回调函数
def apply_async(func, args, *, callback):
result = func(*args)
callback(result)

def print_result(result):
print('Got: ', result)

def add(x, y):
return x + y

apply_async(add, (2, 3), callback=print_result)
# ----------------------------------------------------------





原文地址:https://www.cnblogs.com/fqfanqi/p/8436884.html