first edited October 26, 2017, Thursday
Summary
I. Last Class review
Two. Decorative Device
Three. Adorner supplement
Homework
Summary today
Summary
References: Alex
- Decorative Device
- Non-parametric adorner
- With reference decorator
I. Last Class review
- Namespaces and Scopes
- Built-in namespaces
- Global namespaces
- Local name space
- Global scope: Built-in namespace, global namespace
- Local scope: Local namespace
- function nesting and nesting scopes
- Function object
- Closed Package
Two. Decorative Device
- Why use adorners and open closure principles
- What is an adorner?
- Simple implementation of a non-parametric adorner
import timedef timmer(func): def wrapper(): start_time = time.time() func() stop_time = time.time() print(‘run time is %s ‘ % (stop_time - start_time)) return wrapper@timmer #index=timmer(index)def index(): time.sleep(3) print(‘welcome to oldboy‘)index() #wrapper()
- Non-parametric decorator modifier part1
import timedef timmer(func): def foo(*args,**kwargs): start_time = time.time() func(*args,**kwargs) stop_time = time.time() print(‘run time is %s‘ % (stop_time - start_time)) return foo@timmer #index = timmer(index)def index(name): time.sleep(2) print(‘welconme to my home! %s‘ % name)@timmer #auth = timmer(auth)def auth(name,passwd): print(name,passwd)index(‘egon‘) #foo(‘egon‘)auth(‘liuyang‘,‘123‘) #foo(‘liuyang‘,‘123‘)
- Non-parametric decorator modifier part2
import timedef timmer(func): def foo(*args,**kwargs): start_time = time.time() res = func(*args,**kwargs) stop_time = time.time() print(‘run time is %s ‘% (stop_time - start_time)) return res return foo@timmer # my_max = timmer(my_max)def my_max(x,y): res = x if x > y else y return resres = my_max(2, 3) #foo(2, 3)print(res)
- With reference decorator
def auth2(auth_type): def auth(func): def foo(*args,**kwargs): name = input(‘username: ‘).strip() passwd = input(‘passwd:‘) if auth_type == ‘sql‘: if name == ‘liuyang‘ and passwd == ‘123‘: print(‘auth successful‘) res = func(*args,**kwargs) return res else: print(‘auth error‘) else: print(‘还没学会‘) return foo return auth@auth2(auth_type = ‘sql‘) #index = auth(index)def index(): print(‘welcome to index page‘)index() #foo()
Three. Adorner supplement
- Function plus multiple non-parametric adorners
@ccc@bbb@aaadef func():
- Function plus a plurality of parametric adorners
@ccc(‘c‘)@bbb(‘b‘)@aaa(‘a‘)def func(): passfunc=ccc(‘c‘)(bbb(‘b‘)(aaa(‘a‘)(func)))
Homework
- No
Summary today
- Ready to be sorted
Python Full Stack road Day20