定义无参装饰器函数
return 午餐装饰器函数名
def creat_tag(name):
def tag(f):
def new_f(*args, **kwargs):
result = f(*args, **kwargs)
return f'<{name}>{result}{name}>'
return new_f
return tag
@creat_tag('a')
def func1():
return 'hello'
print(func1()) # hello
# 练习:写个装饰器将原函数的返回值加上指定的数
def add_number(num):
def number(f):
def new_f(*args, **kwargs):
result = f(*args, **kwargs)
if type(result) in (int, float, bool, complex):
return result + num
return result
return new_f
return number
@add_number(10)
def func2(a):
return a*2
print(func2(10)) # 30
list1 = [1, 20, 4, 56]
i1 = iter(list1)
print(i1) #
print(i1, type(i1)) #
# print(len(i1)) # 迭代器无法通过len统计元素的个数
循环体
i2 = iter('hello')
print(next(i2)) # h
# i3遍历结束的时候会变成空的迭代器
i3 = iter(range(5))
for x in i3:
print(f'x:{x}')
'''
x:0
x:1
x:2
x:3
x:4
'''
print(list(i3)) # [],i3变成了空的迭代器,转换成列表就是空列表
i4 = iter(range(0, 10, 2))
# i4转换成列表之后会变成空的迭代器
print(list(i4)) # [0, 2, 4, 6, 8]
# print(next(i4)) # 迭代器里面已经空了,会报错 StopIteration
def func1():
print('========')
return 100
result = func1()
print(f'result:{result}')
# ========
# result:100
def func2():
yield
print('========')
return 100
result = func2() # result就是一个生成器
print(f'result:{result}') # result:
def func3():
yield
yield 10
yield 100
gen1 = func3()
print(next(gen1)) # None
print(next(gen1)) # 10
print(next(gen1)) # 100
def func4():
for x in range(5):
yield 10**2
gen2 = func4()
for x in gen2:
print(f'x:{x}')
def func4():
print('==============1========')
yield 10
print('========2======')
yield 20
yield 30
yield 40
gen3 = func4()
print('第一次取:', next(gen3))
# ==============1========
# 第一次取: 10
print('第二次取:', next(gen3))
# ========2======
# 第二次取: 20
# 练习:写一个生成器能够产生指定前缀指定长度的学号
# 1 -> 001; 23 -> 023
def add_prefix_length(prefix, length):
for x in range(1, 10**length):
result = prefix + str(x).zfill(length)
yield result
nums = add_prefix_length('py', 3)
print(nums) #
print(next(nums)) # py001
for _ in range(10):
print(next(nums))
print('==:', next(nums))
# 1)第一种导入方式:import
import test
print(test.test_a) # 100
# 2)第二种导入方式
from test import test_a
print(test_a) # 100
# 3)第三种导入方式:模块重命名
import test as TS
print(TS.test_a) # 100
# 4)第四种导入方式:变量重命名
from test import test_a as new_a
print(new_a)
if __name__ == '__main__':