在方法的开头和结尾做一些事情

dil*_*gar 12 python class python-3.x

是否有一种简单的方法可以在课程中的每个函数的开头和结尾处执行某些操作?我已经调查了__getattribute__,但我认为在这种情况下我不能使用它吗?

这是我正在尝试做的简化版本:

class Thing():
    def __init__(self):
        self.busy = False

    def func_1(self):
        if self.busy: 
            return None
        self.busy = True
          ...
        self.busy = False

    def func_2(self):
        if self.busy: 
            return None
        self.busy = True
          ...
        self.busy = False
    ...
Run Code Online (Sandbox Code Playgroud)

MSe*_*ert 11

您可以使用装饰器(如果您不了解它们,可以参考PEP-318):

def decorator(method):
    def decorated_method(self, *args, **kwargs):
        # before the method call
        if self.busy:
            return None
        self.busy = True

        # the actual method call
        result = method(self, *args, **kwargs)  

        # after the method call
        self.busy = False

        return result

    return decorated_method

class Thing():
    def __init__(self):
        self.busy = False

    @decorator
    def func_1(self):
        ...

    @decorator
    def func_2(self):
        ...
Run Code Online (Sandbox Code Playgroud)

functools.wraps如果您希望装饰方法"看起来像"原始方法,则可能需要使用.这@decorator只是语法糖,你也可以明确地应用装饰器:

class Thing():
    def __init__(self):
        self.busy = False

    def func_1(self):
        ...

    func_1 = decorator(func_1)  # replace "func_1" with the decorated "func_1"
Run Code Online (Sandbox Code Playgroud)

如果您真的想将它应用于所有方法,您还可以使用类装饰器:

def decorate_all_methods(cls):
    for name, method in cls.__dict__.items():
        if name.startswith('_'):  # don't decorate private functions
            continue 
        setattr(cls, name, decorator(method))
    return cls

@decorate_all_methods
class Thing():
    def __init__(self):
        self.busy = False

    def func_1(self):
        ...

    def func_2(self):
        ...
Run Code Online (Sandbox Code Playgroud)

  • 我只想补充一点,装饰器语法是`some_fun = decorator(some_fun)的语法糖. (3认同)
  • 射击!,打败我;-) (2认同)