Fork me on GitHub

Python编写相关注意事项

1.# -*- coding: utf-8 -*-
代码首部添加这个,不然会报Non_ASCII charater错误

python闭包:实际应用场景1.保持闭包运行完后的环境;

2.根据外部作用域的局部变量来得到不同的结果;类似配置功能的作用

举两例说明:

1.如果你希望函数每次的执行结果,都是基于这个函数的上次的运行结果,那么就应用闭包实现
棋子移动,保留上次棋子移动到得位置
 1 origin=[0,0] #原点
 2 def create(p=origin):
 3       def move(derection,step):
 4             x=p[0] + derection[0]*step
 5             y=p[1] + derection[1]*step
 6             p[0] = x
 7             p[1] = y      
 8             return p
 9        return move
10 
11 >>> print origin
12 [0, 0]
13 >>> play=create()
14 >>> print play([1,0],10)
15 [10, 0]
16 >>> play([0,1],10)
17 [10, 10]       #在前一次执行的基础上移动;
18 >>> pl=create()
19 >>> pl([1,0],10)
20 [20, 10]

 












2.某字段存在于某文件里;这样只要修改相关字段和文件就能提取,代码复用性大大增加。

 1 def  line_confg(name):
 2       def filed(filename):
 3          file=open(filename)
 4           lines=file.readlines()
 5           file.close()
 6           filed_doc=[i for i in lines if name in i ]
 7            return filed_doc
 8        return filed
 9 
10 #调用
11 s1=line_confg("DIR") #某字段
12 print s1("D:\Py\文件相关操作.py") #文件路径
View Code

 






posted @ 2014-04-17 10:40  Kingler  阅读(215)  评论(0)    收藏  举报