我正在尝试使用调用它们时使用的参数之一对类的类方法进行一些验证.
为此,我正在使用类的装饰器将装饰器应用于所需的方法,该方法将使用函数中的一个参数执行验证功能.
这一切都适用于基类(对于这个例子,我将称之为Parent).
但是,如果我创建另一个继承的类Parent(对于此示例我将调用它Child),继承的装饰classmethod不再正常运行.
类cls的classmethod中的参数Child不是Child预期的,而是Parent相反的.
以下面的例子为例
import inspect
def is_number(word):
if word.isdigit():
print('Validation passed')
else:
raise Exception('Validation failed')
class ClassDecorator(object):
def __init__(self, *args):
self.validators = args
def __decorateMethod(self):
def wrapped(method):
def wrapper(cls, word, *args, **kwargs):
for validator in self.validators:
validator(word)
return method(word, *args, **kwargs)
return wrapper
return wrapped
def __call__(self, cls):
for name, method in inspect.getmembers(cls):
if name == 'shout':
decoratedMethod = self.__decorateMethod()(method)
setattr(cls, name, classmethod(decoratedMethod)) …Run Code Online (Sandbox Code Playgroud)