I have had a situation arise where most methods of a class need to raise an exception if called except for one, if a certain condition is False
. It would be possible to go into most methods and write if not condition
such that each method will raise the exception if the condition is not true, but I think it is probably possible to do this somehow with a single decorator on the top of the class.
This question is similar but it involves decorating every method separately, and if I were going to do that, I might as well just put the if
statement into each method.
Here is some code and comments to help communicate it:
CONDITION = True # change to False to test
def CheckMethods():
if CONDITION:
# run all the methods as usual if they are called
pass
else:
# raise an exception for any method which is called except 'cow'
# if 'cow' method is called, run it as usual
pass
@CheckMethods
class AnimalCalls:
def dog(self):
print("woof")
def cat(self):
print("miaow")
def cow(self):
print("moo")
def sheep(self)
print("baa")
a = AnimalCalls()
a.dog()
a.cat()
a.cow()
a.sheep()
Does anyone know how to do this? Have never decorated a class before or tried to check its methods like this.