Python知识点整理(函数篇)

1.作用域

global语句
用于声明一个全局变量

this_is_global = "abc"

def func():
	global this_is_global
	this_is_global = "global"
	print this_is_global
	
func()
print this_is_global

嵌套作用域

Python2.1之前只允许两个作用域:局部作用域和全局作用域。Python2.1之后的便支持嵌套作用域,代码如下所示:
def foo():
	def bar():
		print "bar"
		n = 4
		print m + n
	print "foo"
	m = 3
	bar()
	
foo()
输出:
foo
bar
7

以下代码会报错:
def foo():
	def bar():
		print "bar"
		n = 4
		print m + n
	print "foo"
	bar()
        m = 3
	
foo()
错误:NameError: free variable 'm' referenced before assignment in enclosing scope

搜索作用域

1.python 先从局部作用域开始搜索,没找到则在全局域继续搜索,否则就会抛出 NameError 异常;
2.全局变量能被同名的局部变量所覆盖;
3.变量的作用域受到命名空间的影响。

闭包

如果在一个内部函数里,对在外部的非全局作用域的变量进行引用,那么内部函数就被认为是 closure(闭包)。使用闭包来代替类实现某个功能是个不错的注意。

计数器:
def counter(start_at = 0):
	count = [start_at]
	def incr():
		count[0] += 1
		return count[0]
	return incr

count1 = counter(5)  #新建函数对象
print count1()
print count1()
print count1()

count2 = counter(5)  #新建函数对象
print count2()
print count2()

print count1()
print count1()
print count1()

输出:
6
7
8
6
7
9
10
11

验证器:
def max_length(n):
    def validator(s):
        if len(s) < n:
            return
        raise Exception('Length of string must be less than {0}!'.format(n))
    return validator

生成器

简版:
def simpleGen():
	yield 1
	yield "2->punch!"

myG = simpleGen()
print myG.next()
print myG.next()

for循环版:
from random import randint
def randGen(aList):
	while len(aList) > 0:
		yield aList.pop(randint(0, len(aList) - 1))

for item in randGen(['rock', 'paper', 'scissors']):
	print item

任务队列:
def tt():
	for x in xrange(4):
		yield "tt+" + str(x)

def yy():
	for x in xrange(4):
		yield "yy+" + str(x)
		
from Queue import Queue

class TaskMgr:
	def __init__(self):
		self.task_q = Queue()
		
	def add(self, task):
		self.task_q.put(task)
		
	def run(self):
		while not self.task_q.empty():
			for i in xrange(self.task_q.qsize()):
				try:
					gen = self.task_q.get()
					print gen.next()
				except StopIteration:
					print str(i) + "Stop."
					pass
				else:
					self.task_q.put(gen)
				
t = TaskMgr()
t.add(tt())
t.add(yy())
t.run()



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值