python - what design pattern for pre-do in class function -



python - what design pattern for pre-do in class function -

my class function alway need before (python):

class x: def f1(): #### if check() == false: return; set_a() #### f1_do_something def f2(): #### if check() == false: return; set_a() #### f2_do_something

and want :

class x: def f1(): # auto check-return-set_a() f1_do_something def f2(): # auto check-return-set_a() f2_do_something

i've read design patterns , not know how apply design patterns in case. if there no suitable design patterns, there other solution problem?

you utilize decorator:

#!/usr/bin/env python def check(f, *args, **kwargs): def inner(*args, **kwargs): print 'checking...' homecoming f(*args, **kwargs) homecoming inner class example(object): @check def hello(self): print 'inside hello' @check def hi(self): print 'inside hi' if __name__ == '__main__': illustration = example() example.hello() example.hi()

this snippet print:

checking... within hello checking... within hi

if go route, please check out functools.wrap, makes decorators aware of original function's name , documentation.

python design-patterns

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -