def func(name, alist=[]):
alist.append(name)
print(alist, id(alist))
func(‘alex‘)
func(‘jack‘, [])
func(‘barry‘)
结果:
[‘alex‘] 4547128200
[‘jack‘] 4547126792 #给alist重新赋值,所以内存地址不同
[‘alex‘, ‘barry‘] 4547128200
count = 0
def func():
print(count)
count = 1
func()
结果:
UnboundLocalError: local variable ‘count‘ referenced before assignment
eq1:
def func():
global count
count = 1
print(globals())
func()
print(globals())
count = 5
print(globals())
结果:
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x108ecb710>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘/Users/suncong/PycharmProjects/python_project/day11/复习专用.py‘, ‘__cached__‘: None, ‘func‘: <function func at 0x108f1fe18>}
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x108ecb710>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘/Users/suncong/PycharmProjects/python_project/day11/复习专用.py‘, ‘__cached__‘: None, ‘func‘: <function func at 0x108f1fe18>, ‘count‘: 1}
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x108ecb710>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘/Users/suncong/PycharmProjects/python_project/day11/复习专用.py‘, ‘__cached__‘: None, ‘func‘: <function func at 0x108f1fe18>, ‘count‘: 5}
eq2:
count = 9
def func():
global count
count = 1
print(globals())
func()
print(globals())
结果:
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x1008ef710>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘/Users/suncong/PycharmProjects/python_project/day11/复习专用.py‘, ‘__cached__‘: None, ‘count‘: 9, ‘func‘: <function func at 0x100943e18>}
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x1008ef710>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__file__‘: ‘/Users/suncong/PycharmProjects/python_project/day11/复习专用.py‘, ‘__cached__‘: None, ‘count‘: 1, ‘func‘: <function func at 0x100943e18>}
eq1:
count = 0
def func():
nonlocal count
count = 1
func()
结果:
SyntaxError: no binding for nonlocal ‘count‘ found
eq2:
def func():
count = 0
def inner():
nonlocal count
count = 1
print(locals())
inner()
print(locals())
func()
结果:
{‘inner‘: <function func.<locals>.inner at 0x10c5fa400>, ‘count‘: 0}
{‘inner‘: <function func.<locals>.inner at 0x10c5fa400>, ‘count‘: 1}
def func1():
print(666)
func1()
print(func1)
结果:
666
<function func1 at 0x1072dde18>
def func1():
print(666)
ret = func1
ret()
print(func1, ret)
结果:
666
<function func1 at 0x10ec45e18> <function func1 at 0x10ec45e18>
def func1():
print(666)
def func2():
print(888)
l1 = [func1, func2]
print(l1)
结果:
[<function func1 at 0x105873e18>, <function func2 at 0x105a67400>]
def func1():
print(666)
def func2(x):
x()
func2(func1)
结果:
666
def func1():
print(666)
def func2(x):
return x
ret = func2(func1)
ret()
结果:
666
name = ‘taibai‘
age = 18
msg = f‘我的名字是{name}, 我今年{age}岁‘
print(msg)
结果:
我的名字是taibai, 我今年18岁
name = ‘taibai‘
age = 18
msg = f‘我的名字是{name}, 我今年{age*2}岁‘
print(msg)
结果:
我的名字是taibai, 我今年36岁
a = 10
b = 20
msg = f‘总金额为:{a*b}‘
print(msg)
结果:
总金额为:200
dic = {‘name‘: ‘alex‘, ‘age‘: 18}
msg = f"我叫{dic.get(‘name‘)}, 我今年{dic.get(‘age‘)}岁"
print(msg)
结果:
我叫alex, 我今年18岁
#还可以结合其他数据类型使用,比如列表也适用
def my_sum(a, b):
return a + b
msg = f"result:{my_sum(10,20)}"
print(msg)
结果:
result:30
1. 定义:可以更新迭代的一个实实在在的值
2. 专业角度:含有‘__iter__‘方法的对象,叫可迭代对象
3. 目前学过的可迭代对象:str,list,tuple,dict,set,range(),文件句柄
1. dir(s):获取对象的所有方法,并将每个方法的名字转换为字符串,作为列表的一个元素,存放在一个列表中
eq1:
s = ‘hi‘
print(dir(s))
结果:
[‘__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‘]
s = ‘hi‘
print(‘__iter__‘ in dir(s))
结果:
True
优点:存储的数据可以直接显示,比较直观,拥有的方法比较多
缺点:存储的数据不能直接取出,占内存
1. 定义:可更新迭代的工具
2. 专业角度:含有‘__iter__‘,‘__next__‘方法的就是迭代器
3. 目前学过的迭代器:文件句柄
with open(‘writefile‘, encoding=‘utf-8‘, mode=‘r‘) as f:
print((‘__iter__‘ in dir(f)) and (‘__next__‘ in dir(f)))
结果:
True
1. 将可迭代转换成迭代器iter()/__iter__()
2. 使用next()/__next__()取出值
3. 一次调用next()/__next__()只取一个值
4. next方法使用的次数要与可迭代对象的个数一致,否则会报StopIteration错误
eq:
l1 = [1, 2, 3, 4, 5, 6]
obj = l1.__iter__()
print(obj.__next__())
print(obj.__next__())
print(obj.__next__())
print(obj.__next__())
print(obj.__next__())
print(obj.__next__())
结果:
1
2
3
4
5
6
eq2:
l1 = [1, 2, 3, 4, 5, 6]
obj = l1.__iter__()
print(obj.__next__())
print(obj.__next__())
print(obj.__next__())
print(obj.__next__())
print(obj.__next__())
print(obj.__next__())
print(obj.__next__())
结果:
StopIteration
优点:
1. 节省内存
2. 惰性机制,每次只取一个值,绝不多取值
缺点:
1. 效率低,时间换空间
2. 不走回头路
eq:
l1 = [1, 2, 3, 4, 5, 6]
obj = l1.__iter__()
for i in range(2):
print(obj.__next__())
for i in range(4):
print(obj.__next__())
结果:
1
2
3
4
5
6
可迭代对象:可迭代对象是一个操作方法较多,数据很直观,但是占用内存比较多的一中数据集
应用:当侧重于对数据可以灵活处理,并且内存空间足够将数据集设置为可迭代地下是明确的选择
迭代器:是一个非常节省内存,可以记录取值位置,可以直接通过循环+next方法取值,但不直观,操作方法较少的一种数据集
应用:当数据量过大,大到足以撑爆你的内存或者你以节省内存为首选因素时
l1 = [1, 2, 3, 4, 5, 6]
obj = l1.__iter__()
while 1:
try:
print(obj.__next__())
except StopIteration:
break
原文:https://www.cnblogs.com/vvbear/p/12996936.html