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

Python 学习笔记(三)Function的更多相关文章

  1. Python 学习笔记三

    笔记三:函数 笔记二已取消置顶链接地址:http://www.cnblogs.com/dzzy/p/5289186.html 函数的作用: 給代码段命名,就像变量給数字命名一样 可以接收参数,像arg ...

  2. webdriver(python) 学习笔记三

    知识点:简单的对象定位 对象的定位应该是自动化测试的核心,要想操作一个对象,首先应该识别这个对象.一个对象就是一个人一样,他会有各种的特征(属性),如比我们可以通过一个人的身份证号,姓名,或者他住在哪 ...

  3. Python学习笔记三

    一. 为什么要使用函数? 函数可以方便阅读代码. 函数可以减少重复代码. 函数可以减少管理操作,减少修改操作. 二. 函数分类: 内置函数:len()   sum()   max()   min() ...

  4. python学习笔记三--字典

    一.字典: 1. 不是序列,是一种映射, 键 :值的映射关系. 2. 没有顺序和位置的概念,只是把值存到对应的键里面. 3. 通过健而不是通过偏移量来读取 4. 任意对象的无序集合 5. 可变长,异构 ...

  5. python学习笔记(三)、字典

    字典是一种映射类型的数据类型.辣么什么是映射呢?如果看过<数据结构与算法>这一本书的小伙伴应该有印象(我也只是大学学习过,嘻嘻). 映射:就是将两个集合一 一对应起来,通过集合a的值,集合 ...

  6. Python学习笔记三:模块

    一:模块 一个模块就是一个py文件,里面定义了一些业务函数.引用模块,可以用import语句导入.导入模块后,通过 模块.函数名(参数)  来使用模块中的函数.如果存在多个同名模块,则前面模块名需要加 ...

  7. python学习笔记(三)高级特性

    一.切片 list.tuple常常截取某一段元素,截取某一段元素的操作很常用 ,所以python提供了切片功能. L=['a','b','c','d','e','f'] #取索引0,到索引3的元素,不 ...

  8. python学习笔记(三):文件操作和集合

    对文件的操作分三步: 1.打开文件获取文件的句柄,句柄就理解为这个文件 2.通过文件句柄操作文件 3.关闭文件. 文件基本操作: f = open('file.txt','r') #以只读方式打开一个 ...

  9. python学习笔记三:函数及变量作用域

    一.定义 def functionName([arg1,arg2,...]): code 二.示例 #!/usr/bin/python #coding:utf8 #coding=utf8 #encod ...

  10. python学习笔记(三)-列表&字典

    列表: 一.列表操作"""Python内置的一种数据类型是列表:list.list是一种有序的集合,可以随时添加和删除其中的元素.比如,列出班里所有同学的名字,就可以用一 ...

随机推荐

  1. iOS开发网络篇--NSURLConnection

    S简介 NSURLConnection: 作用: 1.负责发送请求,建立客户端和服务器的连接发送数据给服务器 2.并收集来自服务器的响应数据 步骤: 1.创建一个NSURL对象,设置请求路径 2.传入 ...

  2. python 利用pop3接收邮件并保存附件

    def SaveAttach():# login the pop3 server ,retrive the new mails ,and download the attachments dstdir ...

  3. 关于ssh的一篇很好的文章

    源地址:http://www.w3hacker.com/?p=156   ssh-agent的manual写得倒是挺详细,可看了好几次都没怎么搞明白.08年在网上找到了非常好的一篇文章,An Illu ...

  4. OpenCV码源笔记——RandomTrees (一)

    OpenCV2.3中Random Trees(R.T.)的继承结构: API: CvRTParams 定义R.T.训练用参数,CvDTreeParams的扩展子类,但并不用到CvDTreeParams ...

  5. NDK(14)Native的char*和Java的String相互转换

    转自: http://www.cnblogs.com/canphp/archive/2012/11/13/2768937.html 首先确保C/C++源文件的字符编码是UTF-8与JAVA的class ...

  6. C#中Dictionary的用法及用途

    Dictionary<string, string>是一个泛型 他本身有集合的功能有时候可以把它看成数组 他的结构是这样的:Dictionary<[key], [value]> ...

  7. OEM - emctl resetTZ agent 设置时区

    [oracle@redhat4 config]$ cd $ORACLE_HOME/redhat4.7_orcl/sysman/config [oracle@redhat4 config]$ pwd/u ...

  8. iOS开发:告诉git不要跟踪UserInterfaceState.xcuserstate

    在xcode中使用git管理项目的技巧: 在多人协作开发的时候,每个开发者都会在项目中的某个目录生成一个 UserInterfaceState.xcuserstate 文件,这个文件大概每5s会刷新一 ...

  9. UVa 12230 (期望) Crossing Rivers

    题意: 从A到B两地相距D,之间有n段河,每段河有一条小船,船的位置以及方向随机分布,速度大小不变.每段河之间是陆地,而且在陆地上行走的速度为1.求从A到B的时间期望. 分析: 我们只要分析每段河的期 ...

  10. 纯css3写的仿真图书翻页效果

    对css3研究越深入,越觉得惊艳.css3说不上是万能的,但是它能实现的效果也超出了我的想象.它的高效率和动画效果的流畅性很多情况下能替代js的作用.个人习惯css3能实现的效果就不会用js,虽然在国 ...