python基础(13):函数名的使用、第一类对象、闭包、迭代器
1. 函数名的运用
1.1 函数名的内存地址
def func():
print("呵呵")
print(func)
结果:
<function func at 0x1101e4ea0>
1.2 函数名可以赋值给其他变量
def func():
print("呵呵")
print(func)
a = func # 把函数当成⼀个变量赋值给另⼀个变量
a() # 函数调⽤ func()
1.3 函数名可以当做容器类的元素
def func1():
print("呵呵")
def func2():
print("呵呵")
def func3():
print("呵呵")
def func4():
print("呵呵")
lst = [func1, func2, func3]
for i in lst:
i()
1.4 函数名可以当做函数的参数
def func():
print("吃了么")
def func2(fn):
print("我是func2")
fn() # 执⾏传递过来的fn
print("我是func2")
func2(func) # 把函数func当成参数传递给func2的参数fn.
1.5 函数名可以作为函数的返回值
def func_1():
print("这⾥是函数1")
def func_2():
print("这⾥是函数2")
print("这⾥是函数1")
return func_2
fn = func_1() # 执⾏函数1. 函数1返回的是函数2, 这时fn指向的就是上⾯函数2
fn() # 执⾏上⾯返回的函数
2. 闭包
def func1():
name = "alex"
def func2():
print(name) # 闭包
func2()
func1()
结果:
alex
def func1():
name = "alex"
def func2():
print(name) # 闭包
func2()
print(func2.__closure__) # (<cell at 0x10c2e20a8: str object at0x10c3fc650>,)
func1()
def outer():
name = "alex"
# 内部函数
def inner():
print(name)
return inner
fn = outer() # 访问外部函数, 获取到内部函数的函数地址
fn() # 访问内部函数
def func1():
def func2():
def func3():
print("嘿嘿")
return func3
return func2
func1()()()
from urllib.request import urlopen
def but():
content = urlopen("http://www.xiaohua100.cn/index.html").read()
def get_content():
return content
return get_content
fn = but() # 这个时候就开始加载校花100的内容
# 后⾯需要⽤到这⾥⾯的内容就不需要在执⾏⾮常耗时的⽹络连接操作了
content = fn() # 获取内容
print(content)
content2 = fn() # 重新获取内容
print(content2)
3. 迭代器
# 对的
s = "abc"
for c in s:
print(c)
# 错的
for i in 123:
print(i)
结果:
Traceback (most recent call last):
File "/Users/sylar/PycharmProjects/oldboy/iterator.py", line 8, in
<module>
for i in 123:
TypeError: 'int' object is not iterable
s = "我的哈哈哈"
print(dir(s)) # 可以打印对象中的⽅法和函数
print(dir(str)) # 也可以打印类中声明的⽅法和函数
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index',
'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower',
'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join',
'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
print(dir(tuple))
print(dir(list))
print(dir(open("护⼠少妇嫩模.txt"))) # ⽂件对象
print(dir(set))
print(dir(dict))
结果:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count',
'index']
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__',
'__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count',
'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__',
'__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__',
'__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__',
'__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed',
'_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing',
'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno',
'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read',
'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell',
'truncate', 'writable', 'write', 'writelines']
['__and__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__',
'__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__',
'__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__',
'__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__',
'__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__',
'__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear',
'copy', 'difference', 'difference_update', 'discard', 'intersection',
'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop',
'remove', 'symmetric_difference', 'symmetric_difference_update', 'union',
'update']
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__',
'__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys',
'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
l = [1,2,3]
l_iter = l.__iter__()
from collections import Iterable
from collections import Iterator
print(isinstance(l,Iterable)) #True
print(isinstance(l,Iterator)) #False
print(isinstance(l_iter,Iterator)) #True
print(isinstance(l_iter,Iterable)) #True
s = "我爱北京天安⻔"
c = s.__iter__() # 获取迭代器
print(c.__next__()) # 使⽤迭代器进⾏迭代. 获取⼀个元素 我
print(c.__next__()) # 爱
print(c.__next__()) # 北
print(c.__next__()) # 京
print(c.__next__()) # 天
print(c.__next__()) # 安
print(c.__next__()) # ⻔
print(c.__next__()) # StopIteration
for i in [1,2,3]:
print(i)
lst = [1,2,3]
lst_iter = lst.__iter__()
while True:
try:
i = lst_iter.__next__()
print(i)
except StopIteration:
break
1. 节省内存2. 惰性机制3. 不能反复, 只能向下执⾏
python基础(13):函数名的使用、第一类对象、闭包、迭代器的更多相关文章
- python 函数名的应用(第一类对象),闭包,迭代器
1.函数名的应用(第一类对象) 函数名的命名规范和变量是一样的 函数名其实就是变量名 可以作为列表中的元素进行储存. def func1(): pass def func2(): pass lst = ...
- 巨蟒python全栈开发-第11天 第一类对象 闭包 迭代器
一.今日主要内容总览(重点) 1.第一类对象->函数名=>变量名 (1)函数对象可以像变量一样进行赋值 (2)还可以作为列表的元素进行使用 (3)还可以作为返回值返回 (4)还可以作为参数 ...
- Python_Mix*函数名的使用以及第一类对象,闭包,迭代器,for循环的内部机制
一:函数名的应用(第一类对象) 函数名的命名规范和变量是一样的,函数名其实就是变量名, 0)函数名可以赋值给其他变量 def func(): #定义一个名为func的函数 print('my ange ...
- python 第一类对象 闭包 迭代器
########################总结########################### 1. 函数名 -> 第一类对象 函数名就是变量名. 函数可以赋值 函数可以作为集合类的 ...
- Python基础之 函数名,闭包,和迭代器
1.函数名作用 函数名本质上就是函数的内存地址或对象. 1.可以被引用 2.可以被当作容器类型的元素 3.可以当作函数的参数和返回值 4.如果记不住的话,那就记住一句话,就当普通变量用 2.闭包 什么 ...
- python基础之函数名的使用,闭包以及迭代器
内容梗概: 1. 函数名的使⽤用以及第⼀一类对象 2. 闭包 3. 迭代器 1.函数名一. 函数名的运⽤.函数名是一个变量, 但它是⼀个特殊的变量, 与括号配合可以执行函数的变量.1.1 函数名的内存 ...
- 第4章 基础知识进阶 第4.1节 Python基础概念之迭代、可迭代对象、迭代器
第四章 基础知识进阶第十七节 迭代.可迭代对象.迭代器 一. 引言 本来计划讲完元组和字典后就讲列表解析和字典解析,但要理解列表解析和字典解析,就需要掌握Python的高级的类型迭代器,因此本节 ...
- python第一类对象,闭包,迭代器
一.第一类对象 第一类对象 -> 函数名 -> 变量名 1.特征: 函数对象可以像变量一样进行赋值 还可以作为列表的元素进行使用 还可以作为返回值返回 还可 ...
- day11 第一类对象 闭包 迭代器
今日主要内容: 1 . 第一类对象 -->函数名--> 变量名 2. 闭包 -->函数的嵌套 3. 迭代器 --> 固定的思想 for 循环 第一类对象 : 函数对象介意向变 ...
随机推荐
- 【RTOS】基于V7开发板的最新版uCOS-III V3.07.03程序模板,含MDK和IAR,支持uC/Probe,与之前版本变化较大
模板下载: 链接:https://pan.baidu.com/s/1_4z_Lg51jMT87RrRM6Qs3g 提取码:2gns 对MDK的AC6也做了支持:https://www.cnblog ...
- IT兄弟连 HTML5教程 CSS3揭秘 小结及习题
小结 CSS3对于开发者来说,给web应用带来了更多的可能性,极大提高了开发效率.CSS3在选择器上的支持可谓是丰富多彩,使得我们能够灵活的控制样式,而不必为元素进行规范化的命名.CSS3支持的动画类 ...
- windows本地连不上虚拟机redis服务完美解决
检查本机与虚拟机是否可以互相ping通,如本机IP:192.168.22.111 虚拟机IP:192.168.44.129 (设置虚拟机静态IP已设置) 本机 win+R 输入cmd 进入dos 输 ...
- Windows鼠标右键新建中增加新建md文件
1.新建一个文本文件,拷贝一下内容到其中: Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\.md\ShellNew] "Nu ...
- mybatis的mapper.xml中使用java类中的全局变量
select * from demo where status = '${@cn.jichi.Global@zz}'
- Python进程池multiprocessing.Pool的用法
一.multiprocessing模块 multiprocessing模块提供了一个Process类来代表一个进程对象,multiprocessing模块像线程一样管理进程,这个是multiproce ...
- 松软科技web课堂:JavaScript 注释
JavaScript 注释用于解释 JavaScript 代码,增强其可读性. JavaScript 注释也可以用于在测试替代代码时阻止执行. 单行注释 单行注释以 // 开头. 任何位于 // 与行 ...
- flutter 下拉加载+下拉加载
功能: 1.下拉加载 2.上拉加载 3.显示加载图标 4.更新列表数据,隐藏加载图标 flutter库: flutter_spinkit: ^3.1.0 加载图标 其他:加载列表需要列表,基于上一节的 ...
- jquery.wordexport.js打印echarts.js画出的柱状图
jquery.wordexport.js打印echarts.js画出的柱状图. echarts画出的图是不能直接打印出来的(echarts的柱状图是用canvas画出来的),而jquery.worde ...
- [转]Sumifs函数多条件求和的9个实例
本文转自:http://m.officezhushou.com/sumif/5187.html 第一部分:sumifs函数用法介绍 excel中sumifs函数是Excel2007以后版本新增的多条件 ...