cls在装饰类的继承classmethod中的行为

Oct*_*Oct 4 python inheritance class-method python-decorators

我正在尝试使用调用它们时使用的参数之一对类的类方法进行一些验证.

为此,我正在使用类的装饰器将装饰器应用于所需的方法,该方法将使用函数中的一个参数执行验证功能.

这一切都适用于基类(对于这个例子,我将称之为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))
        return cls


@ClassDecorator(is_number)
class Parent(object):

    @classmethod
    def shout(cls, word):
        print('{} is shouting {}'.format(cls, word))

    @classmethod
    def say(cls):
        print('{} is talking'.format(cls))


class Child(Parent):
    pass


Parent.shout('123')
Child.shout('321')
Run Code Online (Sandbox Code Playgroud)

将导致以下输出:

Validation passed
<class '__main__.Parent'> is shouting 123
Validation passed
<class '__main__.Parent'> is shouting 321
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  • 为什么Child使用Parentcls 调用class方法
  • 是否有可能使用这种设计来获得想要的行为?

PS:我在Python 2.7.10和Python 3.5.2上都试过这个并且已经有了相同的行为

Mar*_*ers 6

你正在装饰绑定类方法 ; 正是这个对象在被调用时保持Parent并将其传递给原始shout函数; cls你的wrapper()方法中绑定的任何内容都不会被传入和忽略.

首先解开classmethods,你可以使用__func__属性获取底层函数对象:

def __call__(self, cls):
    for name, method in inspect.getmembers(cls):
        if name == 'shout':
            decoratedMethod = self.__decorateMethod()(method.__func__)
            setattr(cls, name, classmethod(decoratedMethod))
    return cls
Run Code Online (Sandbox Code Playgroud)

您现在必须考虑到您的包装器也在处理未绑定的函数,因此传递cls参数或手动绑定:

# pass in cls explicitly:
return method(cls, word, *args, **kwargs)

# or bind the descriptor manually:
return method.__get__(cls)(word, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)