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
Python 学习笔记(三)Function的更多相关文章
- Python 学习笔记三
笔记三:函数 笔记二已取消置顶链接地址:http://www.cnblogs.com/dzzy/p/5289186.html 函数的作用: 給代码段命名,就像变量給数字命名一样 可以接收参数,像arg ...
- webdriver(python) 学习笔记三
知识点:简单的对象定位 对象的定位应该是自动化测试的核心,要想操作一个对象,首先应该识别这个对象.一个对象就是一个人一样,他会有各种的特征(属性),如比我们可以通过一个人的身份证号,姓名,或者他住在哪 ...
- Python学习笔记三
一. 为什么要使用函数? 函数可以方便阅读代码. 函数可以减少重复代码. 函数可以减少管理操作,减少修改操作. 二. 函数分类: 内置函数:len() sum() max() min() ...
- python学习笔记三--字典
一.字典: 1. 不是序列,是一种映射, 键 :值的映射关系. 2. 没有顺序和位置的概念,只是把值存到对应的键里面. 3. 通过健而不是通过偏移量来读取 4. 任意对象的无序集合 5. 可变长,异构 ...
- python学习笔记(三)、字典
字典是一种映射类型的数据类型.辣么什么是映射呢?如果看过<数据结构与算法>这一本书的小伙伴应该有印象(我也只是大学学习过,嘻嘻). 映射:就是将两个集合一 一对应起来,通过集合a的值,集合 ...
- Python学习笔记三:模块
一:模块 一个模块就是一个py文件,里面定义了一些业务函数.引用模块,可以用import语句导入.导入模块后,通过 模块.函数名(参数) 来使用模块中的函数.如果存在多个同名模块,则前面模块名需要加 ...
- python学习笔记(三)高级特性
一.切片 list.tuple常常截取某一段元素,截取某一段元素的操作很常用 ,所以python提供了切片功能. L=['a','b','c','d','e','f'] #取索引0,到索引3的元素,不 ...
- python学习笔记(三):文件操作和集合
对文件的操作分三步: 1.打开文件获取文件的句柄,句柄就理解为这个文件 2.通过文件句柄操作文件 3.关闭文件. 文件基本操作: f = open('file.txt','r') #以只读方式打开一个 ...
- python学习笔记三:函数及变量作用域
一.定义 def functionName([arg1,arg2,...]): code 二.示例 #!/usr/bin/python #coding:utf8 #coding=utf8 #encod ...
- python学习笔记(三)-列表&字典
列表: 一.列表操作"""Python内置的一种数据类型是列表:list.list是一种有序的集合,可以随时添加和删除其中的元素.比如,列出班里所有同学的名字,就可以用一 ...
随机推荐
- arcengine C# 读写lyr(转)
写lyr { IFeatureLayer LineLayer = axMapControl1.get_Layer(0) as IFeatureLayer; ILayerFile ...
- Android 多线程断点下载
package com.itheima.mutiledownloader; import java.io.BufferedReader; import java.io.File; import jav ...
- thrift总结
定义: Apache Thrift是一个facebook建立的RPC框架,现在是一个Apache的顶级项目.Thrift允许通过一个跨语言的定义文件的方式定义数据类型和服务接口,[这个文件]作为[RP ...
- 海明距离hamming distance
仔细阅读ORB的代码,发现有很多细节不是很明白,其中就有用暴力方式测试Keypoints的距离,用的是HammingLUT,上网查了才知道,hamming距离是相差位数.这样就好理解了. 我理解的Ha ...
- AndroidJNI 调用JAVA(转)
转自:http://www.cnblogs.com/likwo/archive/2012/05/21/2512400.html 1. JNIEnv对象 对于本地函数 JNIEXPORT ...
- 自定义tab bar控件 学习资料
http://blog.csdn.net/zoeice/article/details/8068671 import java.util.Vector; import android.content. ...
- apk反编译(8)如何完全防止反编译?
在android 的应用很难做到完全防止反编译,即使用ProGuard混淆的后,也能得到smali代码,这个语法也很简单,很容易理解. 只能通过增加破解难度和成本,使破解者失去耐心. 其中一个常见解决 ...
- NFC(2)NFC、蓝牙和红外之间的差异
NFC(2)NFC.蓝牙和红外之间的差异表
- bzoj2489
这种题完全可以暴力找规律,暴力打表各种搞法 这里有一篇比较全面的题解:http://acm.uestc.edu.cn/bbs/read.php?tid=3698&page=1&tore ...
- UVa 120 Stacks of Flapjacks【构造法】
题意:给出n张煎饼,从上到下输入,每张煎饼上面都有一个数字,厨师每次可以选择第k张煎饼,进行翻转操作,设计一种方法使得所有煎饼按照从小到大排序(最上面的煎饼最小) 首先是这个翻转的操作,如下图 如图所 ...