您可以使用装饰(如果你不知道他们,你可以参考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):
...
如果您希望装饰的方法“看起来像”原始方法,则可能需要使用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"
如果你真的想将它应用到所有的方法,你还可以使用类装饰:
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):
...
想知道为什么要这样做? – abccd
@abccd你的意思是他为什么要使用'self.busy'那样? –
是的,这就是我的意思 – abccd