• Python 学习笔记(三)Function


    python引用变量的顺序: 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量

    1. Scope:

    • If a variable is assigned inside a def, it is local to that function.
    • If a variable is assigned in an enclosing def, it is nonlocal to nested functions.
    • If a variable is assigned outside all defs, it is global to the entire file.

    • global makes scope lookup begin in the enclosing module’s scope and allows
    names there to be assigned. Scope lookup continues on to the built-in scope if the
    name does not exist in the module, but assignments to global names always create
    or change them in the module’s scope.
    • nonlocal restricts scope lookup to just enclosing defs, requires that the names already
    exist there, and allows them to be assigned. Scope lookup does not continue
    on to the global or built-in scopes.

    global关键字用来在函数或其他局部作用域中使用全局变量。但是如果不修改全局变量也可以不使用global关键字。

    >>> gcount = 0
    >>> def func():
    ...     print(gcount)
    ...     
    >>> def func_count():
    ...     global gcount
    ...     gcount +=1
    ...     return gcount
    ... 
    >>> def func_count_test():
    ...     print(func_count())
    ...     print(func_count())
    1
    2

    nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量。

    >>> def tester(start):
    ... state = start # Each call gets its own state
    ... def nested(label):
    ... nonlocal state # Remembers state in enclosing scope
    ... print(label, state)
    ... state += 1 # Allowed to change it if nonlocal
    ... return nested
    ...
    >>> F = tester(0)
    >>> F('spam') # Increments state on each call
    spam 0
    >>> F('ham')
    ham 1
    >>> F('eggs')
    eggs 2
    >>> spam = 99
    >>> def tester():
    ... def nested():
    ... nonlocal spam # Must be in a def, not the module!
    ... print('Current=', spam)
    ... spam += 1
    ... return nested
    ...
    SyntaxError: no binding for nonlocal 'spam' found

    2. Arguments

    • Immutable arguments are effectively passed “by value.” (int,string,tuple) (复制)
    • Mutable arguments are effectively passed “by pointer.” (list, dictionary) (引用)
    >>> def changer(a, b): # Arguments assigned references to objects
    ... a = 2 # Changes local name's value only
    ... b[0] = 'spam' # Changes shared object in-place
    ...
    >>> X = 1
    >>> L = [1, 2] # Caller
    >>> changer(X, L) # Pass immutable and mutable objects
    >>> X, L # X is unchanged, L is different!
    (1, ['spam', 2])
    def changer(a, b):
    b = b[:] # Copy input list so we don't impact caller
    >>> def multiple(x, y):
    ...     x=2
    ...     y=[3,4]
    ...     return x,y
    ... 
    >>> X =1
    >>> L=[1,2]
    >>> X,L = multiple(X,L)
    >>> X
    2
    >>> L
    [3, 4]
    >>> X,L
    (2, [3, 4])

    参数传递:*代表的是tuple,**代表map

    >>> def echo(*args, **kwargs): print(args, kwargs)
    ...
    >>> echo(1, 2, a=3, b=4)
    (1, 2) {'a': 3, 'b': 4}

    intersect and union:

    def intersect(*args):
      res = []
      for x in args[0]: # Scan first sequence
        for other in args[1:]: # For all other args
          if x not in other: break # Item in each one?
        else: # No: break out of loop
          res.append(x) # Yes: add items to end
      return res
    def union(*args):
      res = []
      for seq in args: # For all args
        for x in seq: # For all nodes
          if not x in res:
            res.append(x) # Add new items to result
      return res
  • 相关阅读:
    C++ 引用的作用和用法
    const和指针
    sizeof的用法
    C++数组初始化的问题
    C++变量的存储类别(动态存储、静态存储、自动变量、寄存器变量、
    c++变量在内存中的存储区域(转)
    C语言的 &数组名 和 数组名的区别
    C语言运算中的数据类型自动转换原则
    链表反转
    常见的排序方法
  • 原文地址:https://www.cnblogs.com/zyf7630/p/3093279.html
Copyright © 2020-2023  润新知