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开发--清理缓存

    ios文章原文 一段清理缓存的代码如下: dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) , ...

  2. 44. Wildcard Matching

    题目: Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single charact ...

  3. Java API —— Collections类

    1.Collections类概述         针对集合操作 的工具类,都是静态方法   2.Collections成员方法         public static <T> void ...

  4. 随机森林——Random Forests

    [基础算法] Random Forests 2011 年 8 月 9 日 Random Forest(s),随机森林,又叫Random Trees[2][3],是一种由多棵决策树组合而成的联合预测模型 ...

  5. 自定义View(2)canas绘制基本图形的示例

    效果 代码: void drawSample(Canvas canvas) { /* * 方法 说明 drawRect 绘制矩形 drawCircle 绘制圆形 drawOval 绘制椭圆 drawP ...

  6. 三个Timer

    System.Windows.Forms.Timer System.Timers.Timer System.Threading.Timer 关于这三者的区别,可以参见msdn     https:// ...

  7. R语言字符串函数

    字符串长度: nchar("hello world") #字符串连接:paste) <- value substr("abcdef", 2, 4)[1] ...

  8. MySQL中REGEXP正则表达式使用大全

    REGEXP在mysql是用来执行正则表达式的一个函数 像php中的preg之类的函数了,regexp正则函数如果只是简单的查询使用like即可,但复杂的还是需要使用regexp了,下面我们来看看. ...

  9. mysql设置指定ip远程访问连接实例

    1. 授权用户root使用密码jb51从任意主机连接到mysql服务器: 复制代码代码如下: GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED ...

  10. Eclipse @override报错解决 必须覆盖超类方法

    解决办法:Windows->Preferences-->java->Compiler-->compiler compliance level设置成1.6