第四篇:python基础_4
本篇内容
- 名称空间与作用域
- 闭包函数
- 装饰器
- 迭代器
- 生成器
- 三元表达式
- 列表解析
- 生成器表达式
一、 名称空间与作用域
1.名称空间
存放名字的地方,准确的说名称空间是存放名字与变量值绑定关系的地方。名称空间有分为三类,分别为内置名称空间、全局名称空间、局部名称空间。
加载顺序:内置名称空间 ------> 全局名称空间 ------> 局部名称空间
名字查找顺序:局部名称空间 ------> 全局名称空间 ------> 内置名称空间
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei max = 1
def foo():
max = 2
print(max) foo()
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei max = 1
def foo():
#max = 2
print(max) foo()
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei #max = 1
def foo():
max = 2
print(max) foo()
(1)内置名称空间
在python解释器启动时产生,存放一些python内置的名字。
max() len() int() str() float()
(2)全局名称空间
在执行文件时产生,存放文件级别定义的名字。
x = 1
def func():
y =2
def f1():
pass
print x class foo:
pass if x == 1:
z = 3
(3)局部名称空间
在执行文件的过程中,如果调用了函数,则会产生该函数的局部名称空间。用来存放该函数内定义的名字,该名字在函数调用时生效,在函数调用结束后失效。
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei def foo():
x = 2
print(x) foo()
2.作用域
作用域,即作用的范围。
(1)全局作用域
全局作用域:全局存活,全局有效
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei x = 1
def test():
def test1():
def test2():
print(x)
test2()
test1() test()
(2)局部作用域
局部作用域:临时存活,局部有限
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei x = 1
def test():
def test1():
def test2():
x = 2
print(x)
test2()
test1()
print(x) test()
(3)作用域关系
在函数定义时就已经固定,与调用关系无关,在函数调用时,必须回到函数原来定义的位置去找作用域关系。
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei x = 1
def f1():
x = 1000
def f2():
x = 2000
print(x)
return f2 def foo(func):
func() foo(f1())
二、闭包函数
定义在函数内部的函数,包含对外部作用域名字的引用,而不是对全局作用域名字的引用,那么该内部函数就称为闭包函数。
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei x = 1
def test():
x = 11111
def test_1():
print(x)
return test_1 func = test()
func()
闭包函数的应用
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei import requests
def f1(url):
def f2():
print(requests.get(url).text)
return f2 python_web = f1("https://www.python.org")
baidu_web = f1("https://www.baidu.com") python_web()
baidu_web()
三、装饰器
更改线上代码要遵守开放封闭原则,即对扩展是开放的,对修改是封闭的。
装饰器,装饰它人的工具,装饰器本身可以是任意可调用对象,被装饰的对象本身也可以是任意可调用对象。
装饰器的遵循的原则:1.不修改被装饰对象的源代码2.不修改被调用对象的调用方式。
装饰器的目的是:在遵循1和2原则的前提,为其他新功能函数添加。
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei import time def timeer(func):
def wapper():
start_time = time.time()
func()
stop_time = time.time()
print("run time is %s" %(stop_time - start_time))
return wapper @timeer
def foo():
print("the is foo")
time.sleep(2)
return 123 @timeer
def bar():
print("the is bar")
time.sleep(3) foo()
bar()
有参装饰器
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei if_name = {"users":None}
def login(func):
def wapper(*args,**kwargs):
if if_name["users"]:
return func(*args,**kwargs)
user = input("username:").strip()
passwd = input("password:").strip()
with open("db.txt",encoding="utf-8") as file:
data = eval(file.read())
print(data)
if user in data and passwd == data[user]:
res = func(*args,**kwargs)
if_name["users"] = user
return res
else:
print("login is error")
return wapper @login
def index():
print("the is index,welcome~")
index() @login
def home(name):
print("the is home,%s welcome~" % name)
home("yanglei")
四、迭代器
迭代:是一个重复的过程,每一次重复,都是基于上一次的结果而来。
迭代器对象的优点:
1:提供了一种统一的(不依赖于索引的)迭代方式
2:迭代器本身,比起其他数据类型更省内存
迭代器对象的缺点:
1:一次性,只能往后走,不能回退,不如索引取值灵活
2:无法预知什么时候取值结束,即无法预知长度
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei while True: #单纯的重复
print('你瞅啥') l=['a','b','c','d']
count=0
while count < len(l):
print(l[count])
count+=1
迭代器:
可迭代对象iterable:凡是对象下有__iter__方法:对象.__iter__,该对象就是可迭代对象
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei s='hello'
l=['a','b','c','d']
t=('a','b','c','d')
dic={'name':'yanglei','sex':'m',"age":18}
set1={1,2,3}
f=open('db.txt') s.__iter__()
l.__iter__()
t.__iter__()
dic.__iter__()
set1.__iter__()
f.__iter__()
迭代器对象:可迭代对象执行内置的__iter__方法,得到的结果就是迭代器对象
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei dic={'name':'yanglei','sex':'m',"age":18} i=dic.__iter__()
print(i) #iterator迭代器 i.__next__() #next(i)
print(next(i))
print(next(i))
print(next(i))
print(next(i)) #StopIteration l=['a','b','c','d'] i=l.__iter__()
print(next(i))
print(next(i))
print(next(i))
print(next(i))
print(next(i)) #StopIteration
五、生成器
生成器:在函数内部包含yield关键,那么该函数执行的结果是生成器
生成器就是迭代器
yield的功能:
1 把函数的结果做生迭代器(以一种优雅的方式封装好__iter__,__next__)
2 函数暂停与再继续运行的状态是由yield
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei def func():
print('first')
yield 11111111
print('second')
yield 2222222
print('third')
yield 33333333
print('fourth') g=func()
print(g)
from collections import Iterator
print(isinstance(g,Iterator)) print(next(g))
print('======>')
print(next(g))
print('======>')
print(next(g))
print('======>')
print(next(g)) for i in g: #i=iter(g)
print(i)
六、三元表达式
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei def foo(x):
if x > 3:
return 'ok'
else:
return 'no' x=10
res=x if x > 3 else 'no'
print(res)
七、列表解析
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei nums=[1,2,3,4,5,6]
nums_new=[item**2 for item in nums if item > 3]
print(nums_new)
八、生成器表达式
#!/usr/bin/env pyhon
#encoding: utf-8
#auth: yanglei # [{'name': 'apple', 'price': 333, 'count': 3}, ]
with open('db.txt',encoding='utf-8') as f:
info=[{'name':line.split()[0],
'price':float(line.split()[1]),
'count':int(line.split()[2])} for line in f if float(line.split()[1]) >= 30000]
print(info)
最新文章
- Atitit.自然语言处理--摘要算法---圣经章节旧约39卷概览bible overview v2 qa1.docx
- C#高级编程笔记 Day 5, 2016年9月 13日 (泛型)
- 根据excel表格中的内容更新Sql数据库
- 【RoR win32】新建rails项目找不到script/server的解决办法
- 如何提取HTML代码中img的src地址?
- Oracle中对象权限与系统权限revoke
- How to add “Maven Managed Dependencies” library in build path eclipse
- spring boot 登录注册 demo (三) -- 前后端传递
- ArcGIS API for JavaScript 4.2学习笔记[15] 弹窗内容的格式与自定义格式
- jira7.3.6的安装步骤
- 处理 NCBI taxonomy tree
- Android学习笔记(2):build.grandle的常用设置
- C#深度学习の枚举类型(IEnumerator,IEnumerable)
- Node.js实现网络编程
- linux——系统内核参数优化
- MySQL数据库改名的三种方法
- 前端页面兼容ie8解决方法
- java concurrent 探秘
- Java Web应用中支持跨域请求
- MapReduce C++ Library
热门文章
- 扫描局域网ip的shell
- 【BZOJ3209】花神的数论题(数位DP)
- Flutter Json序列号和反序列化遇到问题 Missing ";part &#39;xxx.g.dart&#39;;";
- C# WinForm 绘制圆角窗体
- https及其背后的加密原理阅读总结
- 安装mysql提示This application requires .NET framework 4.0.
- MySQL - CASE WHEN ... THEN ... ELSE ... END语句
- Linux系统故障分析与排查--日志分析
- 一、Linux 安装
- 三十四、MySQL 函数