函数名是什么?1,函数名就是函数的内存地址a = 2b = ac = bprint(c)2,函数名可以作为变量。def func1(): print(666)f1 = func1()f2 = f1print(f2)3,函数名可以作为函数的参数。def func1(): print(666)def func2(x): print(x) x()print(func1)函数名可以当做函数的返回值。def wapper(): def inner(): print(‘inner‘) return innerret = wapper()ret()globals() 返回全局变量的一个字典locals() 返回【当前位置】的局部变量的字典。def func1(): a = 2 b = 3 print(globals()) print(locals()) def inner(): c = 6 d = 5 print(globals()) print(locals()) inner()print(globals())print(locals())可迭代对象for i in ‘abc‘: print(i)对象内部含有__iter__方法就是可迭代对象。可迭代对象满足可迭代协议。可迭代对象有:str list dict tuple set ranges1 = ‘strs‘print(dir(s1))判断一个对象是否可迭代对象有两种方法:第一种方法:s1 = ‘strs‘dic = {‘name‘:‘alex‘}print(‘__iter__‘in dir(s1))print(‘__iter__‘in dir(dic))第二种方法:from collections import Iterable #Iterable:可迭代from collections import Iterator #Iterator:迭代器print(isinstance(‘alex‘,Iterable)) #isinstance:判断数据类型及功能等等。。。print(isinstance(‘alex‘,Iterator))print(isinstance(‘alex‘,str))迭代器是什么?对象内部含有__iter__方法且含有__next__方法就是迭代器。f=open(‘register.txt‘,encoding=‘utf-8‘)print(‘__iter__‘in dir(f))print(‘__next__‘in dir(f))print(‘__iter__‘in dir(dict))print(‘__next__‘in dir(dict))可迭代对象vs迭代器可迭代对象不能取值,迭代器是可以的可迭代对象--->(转化成)迭代器lis = [1,2,3]itel = lis.__iter__()itel = iter(lis)print(itel)迭代器如何取值?next一次,取一个值print(itel.__next__())print(itel.__next__())print(itel.__next__())1、可迭代对象不能取值,迭代器是可以取值的。2、迭代器非常节省内存。3、迭代器每次只会取一个值。4、迭代器是单向的,一条路走到头。s1 = ‘aqwdew‘1、将可迭代对象转化成迭代器。2、调用__next__方法取值。3、利用异常处理停止报错。iter1 = s1.__iter__()while 1: try: print(iter1.__next__()) except StopIteration: break
原文地址:https://www.cnblogs.com/Clara51/p/9493691.html
时间: 2024-10-09 19:56:25