标签:
让一个函数接受任意数量的位置参数,可以使用一个 * 参数
def avg(first , *rest):
return (first + sum(rest)) / (1 + len(rest))
print(avg(1,2,3))
为了接受任意数量的关键字参数,使用一个以 ** 开头的参数
import html
def make_element(name , value , **attrs):
keyvals = [‘ %s="%s"‘ % item for item in attrs.items()]
attr_str = ‘‘.join(keyvals)
element = ‘<{name}{attrs}>{value}</{name}>‘.format(name=name , attrs=attr_str , value=html.escape(value))
return element
str = make_element(‘item‘ , ‘Albatross‘ , size="large" , quantity=6)
p = make_element(‘p‘ , ‘<spam>‘)
只接受关键字参数的函数
def mininum(*values , clip=None):
m = min(values)
if clip is not None:
m = clip if clip > m else m
return m
minnum = mininum(1,23,43,4,34,3,4, clip=3)
print(minnum)
函数参数注解
>>> def add(x:int , y:int)->int:
... return x+y
...
>>> str = add(2,3)
>>> str
5
>>> help(add)
Help on function add in module __main__:
add(x:int, y:int) -> int
>>> add.__annotations__
{‘y‘: <class ‘int‘>, ‘return‘: <class ‘int‘>, ‘x‘: <class ‘int‘>}
lambda
>>> add = lambda x, y: x + y
>>> add(2,3)
5
lambad 遇到自由变量时
>>> x =10
>>> a = lambda y : x +y
>>> x = 20
>>> b = lambda y:x+ y
>>> a(10)
30
>>> b(10)
30
>>>
如果你想让某个匿名函数在定义时就捕获到值,可以将那个参数值定义成默认参数
即可,就像下面这样:
>>> x = 10
>>> a = lambda y, x=x: x + y
>>> x = 20
>>> b = lambda y, x=x: x + y
>>> a(10)
20
>>> b(10)
30
partial()
函数允许你给一个或多个参数设置固定的值,减少接下来被调用时的参数个数
def spam(a, b, c, d):
print(a, b, c, d)
>>> from functools import partial
>>> s1 = partial(spam, 1) # a = 1
>>> s1(2, 3, 4)
1 2 3 4
>>> s1(4, 5, 6)
1 4 5 6
>>> s2 = partial(spam, d=42) # d = 42
>>> s2(1, 2, 3)
1 2 3 42
>>> s2(4, 5, 5)
4 5 5 42
>>> s3 = partial(spam, 1, 2, d=42) # a = 1, b = 2, d = 42
>>> s3(3)
1 2 3 42
>>> s3(4)
1 2 4 42
回调函数的使用
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)
Got: 5
>>> apply_async(add, (‘hello‘, ‘world‘), callback=print_result)
Got: helloworld
#闭包函数
def sample():
n = 0
def func():
print(‘n=‘ , n)
def get_n():
return n
def set_n(value):
nonlocal n
n =value
func.get_n = get_n
func.set_n = set_n
return func
f = sample()
f.set_n(1999)
print(f.get_n())
nonlocal 声明可以让我们编写函数来修改内部变量的值
-- dmo --
import sys
class ClosureInstance:
def __init__(self , locals=None):
if locals is None:
locals = sys._getframe(1).f_locals
self.__dict__.update((key ,value) for key , value in locals.items() if callable(value))
def __len__(self):
return self.__dict__[‘__len__‘]()
def Stack():
items = []
def push(item):
items.append(item)
def pop():
return items.pop()
def __len__():
return len(items)
return ClosureInstance()
s = Stack()
s.push(10)
print(s.pop())
标签:
原文地址:http://www.cnblogs.com/zeopean/p/python-method.html