2

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?

Martin Geisler
  • 72,968
  • 25
  • 171
  • 229
nguyên
  • 5,156
  • 5
  • 43
  • 45

1 Answers1

5

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.

Community
  • 1
  • 1
miku
  • 181,842
  • 47
  • 306
  • 310
  • 1
    I suggest decorate your decorator with the function decorator decorator: http://docs.python.org/library/functools.html#functools.wraps – Anders Waldenborg Jan 11 '12 at 06:35
  • @AndersWaldenborg, thanks, added a note to my post. I haven't added it directly in the code, because I wanted to keep it as simple as possible to focus on the idea. – miku Jan 11 '12 at 06:38