nguyên
nguyên

Reputation: 5326

what design pattern for pre-do in class function

My class function alway need do something before like this (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 I want to :

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 about design patterns and I do not know how to apply design patterns in this case. If there is no any suitable design patterns, are there any other solution to this problem?

Upvotes: 2

Views: 121

Answers (1)

miku
miku

Reputation: 188024

You could use a decorator:

#!/usr/bin/env python

def check(f, *args, **kwargs):
    def inner(*args, **kwargs):
        print 'checking...'
        return f(*args, **kwargs)
    return inner

class Example(object):

    @check
    def hello(self):
        print 'inside hello'

    @check
    def hi(self):
        print 'inside hi'

if __name__ == '__main__':
    example = Example()
    example.hello()
    example.hi()

This snippet would print:

checking...
inside hello
checking...
inside hi

If you go this route, please check out functools.wrap, which makes decorators aware of the original function's name and documentation.

Upvotes: 5

Related Questions