Recently I wanted to use Python to write a simple generator, similar specify the type and extent of return specified list;
For example we want an integer of 0 to 3, and then I just need to specify:
Minimum: 0,
Maximum: 3,
Step: 1
A [0,1,2,3] List Return
The idea is to use Python decorators to play in def decorator, passing when called decorator interior replacement method parameter values
code show as below:
1 # coding=utf-8 2 3 def integer(min=0, max=100, step=1): 4 def deco(func): 5 def wrapper(val): 6 val = [] 7 for i in range(min, max, step): 8 val.append(i) # 将入参修改掉 9 return func(val) 10 return wrapper 11 return deco 12 13 14 @integer(1, 40) 15 def id(val): 16 return val 17 18 a = id(None) 19 print(a)
The value of such a printed list of what I want:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
Than Java annotation to write much more convenient, Python Dafa is good!