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是一种有序的集合,可以随时添加和删除其中的元素.比如,列出班里所有同学的名字,就可以用一 ...
随机推荐
- linux下安装Apache(https) 服务器证书安装配置指南
一. 安装准备 1. 安装Openssl 要使Apache支持SSL,需要首先安装Openssl支持.推荐下载安装openssl-0.9.8k.tar.gz 下载Openssl:http: ...
- React Jest测试
一. var jest = require('jest'); jest.dontMock('../CheckboxWithLabel.js'); describe('CheckboxWithLabel ...
- HTML5 文件API(二)
1.FileSystem概述及浏览器检 2.申请磁盘配额 3.创建文件
- JavaScript基础精华03(String对象,Array对象,循环遍历数组,JS中的Dictionary,Array的简化声明)
String对象(*) length属性:获取字符串的字符个数.(无论中文字符还是英文字符都算1个字符.) charAt(index)方法:获取指定索引位置的字符.(索引从0开始) indexOf(‘ ...
- Django admin site(二)ModelAdmin methods
ModelAdmin methods save_model(request, obj, form, change) 此方法为admin界面用户保存model实例时的行为.request为HttpReq ...
- 网站TCP链接暴增
昨天上线后,TCP链接暴增,红点增多. 问题在查.其中有一部分,多线程修改,突破了线程数 64的限制.线程内,会发起网络请求. 怀疑是热点之一.其他的部分也有修改,也被怀疑.准备下次,2部分分开上线. ...
- Setup Oracle 11gR2 for Redhat Linux AS 4 Update 7 x64
Setup Oracle 11gR2 for Redhat Linux AS 4 Update 7 x64 1. checking linux version. [root@localhost ~]# ...
- MemSQL start[c]up Round 2 - online version(DP)
只有小写字母 那>=2600的直接找单字母串长度大于等于100的就可以了 <2600 的dp找最长回文串 #include <iostream> #include<cst ...
- BZOJ3856: Monster
题目:http://www.lydsy.com/JudgeOnline/problem.php?id=3856 题解:怎么乱搞一下都可以把 代码: #include<cstdio> #in ...
- <一>SQL优化1-4
第一条:去除在谓词列上编写的任何标量函数 --->在select 显示列上使用标量函数是可以的.但在where语句后的过滤条件部分对列使用函数,需要考虑.因为执行sql的引擎会因为 ...