I have some python objects with some methods in which I would like to do some check at the beginning, depending on this check, the method code will be executed or execution will be called. Instead of repeating the verification code at the beginning of each method, although I am making a decorator, I also want the decorator to be embedded inside the class itself, since it is closely related to it. So basically:
instead of this
class A(object):
def a_method(self):
if self.check_var is True:
(some_code)
else:
raise Exception
I would like to have it
class A(object):
def decorator(function):
def function_wrapper(self, *args, **kwargs):
if self.check_var is True:
return function(self, *args, **kwargs)
else:
raise Exception
return function_wrapper
@decorator
def a_method(self):
(some_code)
My first question is: am I right about this? or is there a better way. I have many class A methods that should have this check, so I don’t want to copy the code unnecessarily.
: , , A . , A . , @classmethod, , , !
, - :
class A(object):
@classmethod #maybe
def decorator(function):
def function_wrapper(self, *args, **kwargs):
if self.check_var is True:
return function(self, *args, **kwargs)
else:
raise Exception
return function_wrapper
@decorator
def a_method(self):
(some_code)
class B(A):
@decorator
def b_method(self):
(some_code)
- - ?