zoukankan      html  css  js  c++  java
  • 对python 函数的一些理解

    函数的传参

    让一个函数接受任意数量的位置参数,可以使用一个 * 参数

    1 def avg(first , *rest):
    2 
    3     return (first + sum(rest)) / (1 + len(rest))
    4 
    5 print(avg(1,2,3))

    为了接受任意数量的关键字参数,使用一个以 ** 开头的参数

     1 import html
     2 
     3 def make_element(name , value , **attrs):
     4 
     5     keyvals = [' %s="%s"' % item for item in attrs.items()]
     6 
     7     attr_str = ''.join(keyvals)
     8 
     9     element = '<{name}{attrs}>{value}    </{name}>'.format(name=name , attrs=attr_str  ,            value=html.escape(value))
    10 
    11     return element
    12 
    13  
    14 
    15 str = make_element('item' , 'Albatross' , size="large" , quantity=6)
    16 
    17 p   = make_element('p' , '<spam>')    

    只接受关键字参数的函数

     1 def mininum(*values , clip=None):
     2 
     3     m = min(values)
     4 
     5     if clip is not None:
     6 
     7         m = clip if clip > m else m 
     8 
     9     return m
    10 
    11  
    12 
    13 minnum = mininum(1,23,43,4,34,3,4, clip=3)
    14 
    15 print(minnum)
    16 
    17      

    函数参数注解

     1 >>> def add(x:int , y:int)->int:
     2 
     3 ...     return x+y
     4 
     5 ...
     6 
     7 >>> str = add(2,3)
     8 
     9 >>> str
    10 
    11 5
    12 
    13 >>> help(add)
    14 
    15 Help on function add in module __main__:
    16 
    17  
    18 
    19 add(x:int, y:int) -> int
    20 
    21  
    22 
    23 >>> add.__annotations__
    24 
    25 {'y': <class 'int'>, 'return': <class 'int'>, 'x': <class 'int'>}

    匿名或内联函数

    1 lambda
    2 
    3 >>> add = lambda x, y: x + y
    4 
    5 >>> add(2,3)
    6 
    7 5

    lambad 遇到自由变量时

     1 >>> x =10
     2 
     3 >>> a = lambda y : x +y
     4 
     5 >>> x = 20
     6 
     7 >>> b = lambda y:x+ y
     8 
     9 >>> a(10)
    10 
    11 30
    12 
    13 >>> b(10)
    14 
    15 30
    16 
    17 >>>

    如果你想让某个匿名函数在定义时就捕获到值,可以将那个参数值定义成默认参数

    即可,就像下面这样:

     1 >>> x = 10
     2 
     3 >>> a = lambda y, x=x: x + y
     4 
     5 >>> x = 20
     6 
     7 >>> b = lambda y, x=x: x + y
     8 
     9 >>> a(10)
    10 
    11 20
    12 
    13 >>> b(10)
    14 
    15 30
    16 
    17  
    18 
    19 partial() 

    函数允许你给一个或多个参数设置固定的值,减少接下来被调用时的参数个数

     1 def spam(a, b, c, d):
     2 
     3 print(a, b, c, d)
     4 
     5  
     6 
     7 >>> from functools import partial
     8 
     9 >>> s1 = partial(spam, 1) # a = 1
    10 
    11 >>> s1(2, 3, 4)
    12 
    13 1 2 3 4
    14 
    15 >>> s1(4, 5, 6)
    16 
    17 1 4 5 6
    18 
    19 >>> s2 = partial(spam, d=42) # d = 42
    20 
    21 >>> s2(1, 2, 3)
    22 
    23 1 2 3 42
    24 
    25 >>> s2(4, 5, 5)
    26 
    27 4 5 5 42
    28 
    29 >>> s3 = partial(spam, 1, 2, d=42) # a = 1, b = 2, d = 42
    30 
    31 >>> s3(3)
    32 
    33 1 2 3 42
    34 
    35 >>> s3(4)
    36 
    37 1 2 4 42

    回调函数的使用

     1 def  apply_async(func, args, *, callback):
     2 
     3 result = func(*args)
     4 
     5 callback(result)
     6 
     7  
     8 
     9 >>> def print_result(result):
    10 
    11 ... print('Got:', result)
    12 
    13  
    14 
    15 >>> def add(x, y):
    16 
    17 ... return x + y
    18 
    19  
    20 
    21 >>> apply_async(add, (2, 3), callback=print_result)
    22 
    23 Got: 5
    24 
    25 >>> apply_async(add, ('hello', 'world'), callback=print_result)
    26 
    27 Got: helloworld

    闭包函数

     1 #闭包函数
     2 
     3 def sample():
     4 
     5     n = 0
     6 
     7     def func():
     8 
     9         print('n=' , n)
    10 
    11  
    12 
    13     def get_n():
    14 
    15         return n
    16 
    17  
    18 
    19     def set_n(value):
    20 
    21         nonlocal n
    22 
    23         n =value
    24 
    25  
    26 
    27     func.get_n = get_n
    28 
    29     func.set_n = set_n
    30 
    31     return func
    32 
    33  
    34 
    35 f = sample()
    36 
    37 f.set_n(1999)
    38 
    39 print(f.get_n())            

    nonlocal 声明可以让我们编写函数来修改内部变量的值

    -- dmo --

     1 import sys
     2 
     3 class ClosureInstance:
     4 
     5     def __init__(self , locals=None):
     6 
     7         if locals is None:
     8 
     9         locals = sys._getframe(1).f_locals
    13         self.__dict__.update((key ,value) for key , value in locals.items() if callable(value))
    14 
    16 
    17     def __len__(self):
    18 
    19         return self.__dict__['__len__']()
    20 
    21  
    22 
    23 def Stack():
    24 
    25     items = [] 
    26 
    27     def push(item):
    28 
    29         items.append(item)
    30 
    31  
    32 
    33     def pop():
    34 
    35         return items.pop()
    36 
    37  
    38 
    39   def __len__():
    40 
    41       return len(items)
    42 
    43  
    44 
    45   return ClosureInstance()
    46 
    47  
    48 
    49  
    50 
    51 s = Stack()
    52 
    53 s.push(10)
    54 
    55 print(s.pop())                    
  • 相关阅读:
    摒弃FORM表单上传图片,异步批量上传照片
    小功能——简单代码实现邮箱发送邮件
    小工具 ——快速生成验证码
    [转]C++11 多线程
    [转]线性插值&双线性插值&三线性插值
    [转]第四章 使用OpenCV探测来至运动的结构——Chapter 4:Exploring Structure from Motion Using OpenCV
    windows的Timer和写文件方式串口注意!
    OPENCV3.1+VS 坑我笔记!
    最简单的PC机串口通信程序
    用MFC时,如果程序崩溃,检查内存,然后注意GDI数量,在任务管理器里选项-查看列-GDI数量
  • 原文地址:https://www.cnblogs.com/zeopean/p/python-method.html
Copyright © 2011-2022 走看看