Obs: Of course I could just create a method that validate, and call this method inside all my other methods. But I wonder if it's posible to do something I've been thinking for a while.
WHAT I NEED:
I have a class where all my methods should verify if the parameter (an object) that it receives is not None and if it has a specific method. Let's make it simple.
I wonder if there is something simple like the following code.
HERE IS AN EXAMPLE:
def validate(obj):
return not obj or obj.can_validate()
class MyClass:
def __init__(self):
pass
@validate(obj)
def my_method_1(self, obj):
print(obj)
@validate(obj)
def my_method_2(self, obj):
print(obj)
@validate(obj)
def my_method_3(self, obj):
print(obj)
class Validator1:
def __init__(self):
pass
class Validator2:
def __init__(self):
pass
def can_validate(self):
pass
my_class = MyClass()
obj_1 = None
obj_2 = Validator1()
obj_3 = Validator2()
print(x.my_method_1(obj_1))
print(x.my_method_2(obj_2))
print(x.my_method_3(obj_3))
# The output would be something like this>>
# output:
# <empty line because obj_1 is None>
# <empty line because obj_2 has no method can_validate()>
# __Class__...something <since it's not none and has can_validate() method>
If there isn't anything similar to that, what should be most clean and correct way to do that, avoiding code repetition and "a ton of code"?