在 Class 的所有方法中验证相同的东西。避免代码重复

Validate same thing in all methods from a Class. Avoiding code repetition

Obs:当然我可以只创建一个验证方法,然后在我所有其他方法中调用这个方法。但是我想知道是否可以做一些我一直在想的事情。

我需要什么:

我有一个 class,我的所有方法都应验证它接收的参数(对象)是否不是 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>

如果没有类似的东西,最干净和正确的方法应该是什么,避免代码重复和"a ton of code"?

对现有代码进行最少的更改:

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