您可以使用裝飾(如果你不知道他們,你可以參考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