Obs:当然,我可以创建一个验证方法,并在所有其他方法中调用此方法。但我想知道是否可以做我已经思考了一段时间的事情。
我需要什么:
我有一个类,我的所有方法都应验证其接收的参数(对象)是否不为None以及是否具有特定的方法。让我们简单点吧。
我想知道是否有类似以下代码的简单内容。
这里是一个例子:
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>
如果没有类似的东西,那应该是最干净,最正确的方法来避免代码重复和“大量代码”?
答案 0 :(得分:1)
只需对现有代码进行最少的更改:
def validate(func):
def modified(self, obj):
if obj and hasattr(obj, 'can_validate'):
return func(self, obj)
return None # None will be printed. Change it to '' to print empty line
return modified
class MyClass:
def __init__(self):
pass
@validate
def my_method_1(self, obj):
print(obj)
@validate
def my_method_2(self, obj):
print(obj)
@validate
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
x = 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))
输出:
None
None
<__main__.Validator2 object at 0x7f6185ca9e10>
None