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 循环 第一类对象 : 函数对象介意向变 ...
随机推荐
- pixijs shader 贴图溶解效果教程
pixijs shader 贴图溶解效果教程 我直接贴代码了 没什么好讲解了 稍微有点基础的人应该能看懂 const app = new PIXI.Application({ transparent: ...
- 真正的RISC-V开发板——VEGA织女星开发板开箱评测
前言 由于最近ARM公司要求员工"停止所有与华为及其子公司正在生效的合约.支持及未决约定",即暂停与华为的相关合作,大家纷纷把注意力投向了另一个的处理器架构RISC-V,它是基于精 ...
- SpringBoot2.0 整合 Dubbo框架 ,实现RPC服务远程调用
一.Dubbo框架简介 1.框架依赖 图例说明: 1)图中小方块 Protocol, Cluster, Proxy, Service, Container, Registry, Monitor 代表层 ...
- ASP.NET Core部署系列一:发布到IIS上
前言: 当构建一个ASP.NET Core应用程序并且计划将其运行在IIS中时,你会发现Core应用程序和之前版本的ASP.NET程序在IIS中的运行方式是完全不一样的.与ASP.NET时代不同,AS ...
- Add a Parametrized Action 添加带参数的按钮
In this lesson, you will learn how to add a Parametrized Action. These types of Actions are slightly ...
- JS基础语法---Math对象的案例
系统Max求最大值: var result= Math.max(10,20,30,40); console.log(result); 练习1:自己定义一个对象,实现系统的max的方法 //例子:自 ...
- 在vue组件中设置定时器和清除定时器
由于项目中难免会碰到需要实时刷新,无论是获取短信码,还是在支付完成后轮询获取当前最新支付状态,这时就需要用到定时器.但是,定时器如果不及时合理地清除,会造成业务逻辑混乱甚至应用卡死的情况,这个时就需要 ...
- [转]UIPATH机器人指南
本文转自:https://blog.csdn.net/weixin_33957036/article/details/80907372 介绍 机器人是UiPath的执行代理,可运行Studio中内置的 ...
- Docker系列01-容器初探
关于容器的发展史 关于容器有不得不说的历史故事,以下资料来自于互联网收集整理所得: 容器概念始于 1979 年提出的 UNIX chroot,它是一个 UNIX 操作系统的系统调用,将一个进程及其子进 ...
- CentOS安装docker-compose
一.compose简介 compose是一个定义和运行多容器的docker应用的工具.compose 通过yaml文件配置应用服务,然后仅需一个命令就可以创建和运行所有配置中的服务. 二.compos ...