什么设计模式为课堂功能预先做

ngu*_*yên 2 python design-patterns

我的类函数总是需要在此之前做一些事情(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
Run Code Online (Sandbox Code Playgroud)

我想:

class X:
 def f1():
  # auto check-return-set_A()
  f1_do_something

 def f2():
  # auto check-return-set_A() 
  f2_do_something
Run Code Online (Sandbox Code Playgroud)

我已经阅读过设计模式,在这种情况下我不知道如何应用设计模式.如果没有任何合适的设计模式,是否还有其他解决方案?

mik*_*iku 5

你可以使用一个装饰者:

#!/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()
Run Code Online (Sandbox Code Playgroud)

这段代码会打印出来:

checking...
inside hello
checking...
inside hi
Run Code Online (Sandbox Code Playgroud)

如果你走这条路,请检查functools.wrap,这使得装饰者知道原始功能的名称和文档.