将decorator添加到继承类的方法中?

时间:2018-05-16 08:55:38

标签: python inheritance decorator

我想从类继承只是为了向它的方法添加装饰器。

如果没有重新定义每个基类方法,是否有快捷方式?

2 个答案:

答案 0 :(得分:0)

当然,你可以动态地做到这一点。假设你有一些课程:

>>> class Foo:
...    def bar(self): print('bar')
...    def baz(self): print('baz')
...

还有一位装饰师:

>>> def deco(f):
...    def wrapper(self):
...       print('decorated')
...       return f(self)
...    return wrapper
...

然后继承:

>>> class Foo2(Foo):
...     pass
...

然后遍历原始类,并将装饰器应用于新的子类:

>>> for name, attr in vars(Foo).items():
...     if callable(attr):
...         setattr(Foo2, name, deco(attr))
...

因此...

>>> x = Foo2()
>>> x.bar()
decorated
bar
>>> x.baz()
decorated
baz

现在,使用if callable(attr)可能不够严格。你可能想忽略“dunder”方法,所以改为:

for name, attr in vars(Foo):
    if callable(attr) and not name.startswith('__'):
        setattr(Foo2, name, attr)

可能更合适。取决于你的用例。

只是为了好玩,这里我们也可以使用type构造函数:

In [17]: class Foo:
    ...:     def bar(self): print('bar')
    ...:     def baz(self): print('baz')
    ...:

In [18]: def deco(f):
    ...:     def wrapper(self):
    ...:         print('decorated')
    ...:         return f(self)
    ...:     return wrapper
    ...:

In [19]: Foo3 = type(
    ...:     'Foo3',
    ...:     (Foo,),
    ...:     {name:deco(attr) for name, attr in vars(Foo).items() if callable(attr)}
    ...: )

In [20]: y = Foo3()

In [21]: y.bar()
decorated
bar

In [22]: y.baz()
decorated
baz

答案 1 :(得分:0)

您可以使用类装饰器来封装整个作品

示例代码:

def deco(func):
    """Function decorator"""
    def inner(*args, **kwargs):
        print("decorated version")
        return func(*args, **kwargs)
    return inner

def decoclass(decorator):
    """Class decorator: decorates public methods with decorator"""
    def outer(cls):
        class inner(cls):
            pass
        for name in dir(cls):
            if not name.startswith("_"):     # ignore hidden and private members
                # print("decorating", name)  # uncomment for tests
                attr = getattr(inner, name)
                setattr(inner, name, decorator(attr))
        return inner
    return outer

class Foo:
    """Sample class""
    def foo(self):
        return "foo in Foo"

然后你可以使用它:

>>> @decoclass(deco)
class Foo2(Foo):
    pass

>>> f = Foo2()
>>> f.foo()
decorated version
'foo in Foo'