簡體   English   中英

編寫將裝飾器應用於所有方法的 class 裝飾器

[英]Writing a class decorator that applies a decorator to all methods

我正在嘗試編寫一個 class 裝飾器,它將裝飾器應用於所有類的方法:

import inspect


def decorate_func(func):
    def wrapper(*args, **kwargs):
        print "before"
        ret = func(*args, **kwargs)
        print "after"
        return ret
    for attr in "__module__", "__name__", "__doc__":
        setattr(wrapper, attr, getattr(func, attr))
    return wrapper


def decorate_class(cls):
    for name, meth in inspect.getmembers(cls, inspect.ismethod):
        setattr(cls, name, decorate_func(meth))
    return cls


@decorate_class
class MyClass(object):

    def __init__(self):
        self.a = 10
        print "__init__"

    def foo(self):
        print self.a

    @staticmethod
    def baz():
        print "baz"

    @classmethod
    def bar(cls):
        print "bar"


obj = MyClass()
obj.foo()
obj.baz()
MyClass.baz()
obj.bar()
MyClass.bar()

它幾乎可以工作,但@classmethod S 需要特殊處理:

$ python test.py
before
__init__
after
before
10
after
baz
baz
before
Traceback (most recent call last):
  File "test.py", line 44, in <module>
    obj.bar()
  File "test.py", line 7, in wrapper
    ret = func(*args, **kwargs)
TypeError: bar() takes exactly 1 argument (2 given)

有沒有辦法很好地處理這個問題? 我檢查@classmethod修飾的方法,但我沒有看到任何可以將它們與其他“類型”方法區分開來的東西。

更新

這是記錄的完整解決方案(使用描述符很好地處理@staticmethod S和@classmethod S,以及aix檢測@classmethod S VS普通方法的技巧):

import inspect


class DecoratedMethod(object):

    def __init__(self, func):
        self.func = func

    def __get__(self, obj, cls=None):
        def wrapper(*args, **kwargs):
            print "before"
            ret = self.func(obj, *args, **kwargs)
            print "after"
            return ret
        for attr in "__module__", "__name__", "__doc__":
            setattr(wrapper, attr, getattr(self.func, attr))
        return wrapper


class DecoratedClassMethod(object):

    def __init__(self, func):
        self.func = func

    def __get__(self, obj, cls=None):
        def wrapper(*args, **kwargs):
            print "before"
            ret = self.func(*args, **kwargs)
            print "after"
            return ret
        for attr in "__module__", "__name__", "__doc__":
            setattr(wrapper, attr, getattr(self.func, attr))
        return wrapper


def decorate_class(cls):
    for name, meth in inspect.getmembers(cls):
        if inspect.ismethod(meth):
            if inspect.isclass(meth.im_self):
                # meth is a classmethod
                setattr(cls, name, DecoratedClassMethod(meth))
            else:
                # meth is a regular method
                setattr(cls, name, DecoratedMethod(meth))
        elif inspect.isfunction(meth):
            # meth is a staticmethod
            setattr(cls, name, DecoratedClassMethod(meth))
    return cls


@decorate_class
class MyClass(object):

    def __init__(self):
        self.a = 10
        print "__init__"

    def foo(self):
        print self.a

    @staticmethod
    def baz():
        print "baz"

    @classmethod
    def bar(cls):
        print "bar"


obj = MyClass()
obj.foo()
obj.baz()
MyClass.baz()
obj.bar()
MyClass.bar()

inspect.isclass(meth.im_self)應該告訴你meth是否是 class 方法:

def decorate_class(cls):
    for name, meth in inspect.getmembers(cls, inspect.ismethod):
        if inspect.isclass(meth.im_self):
          print '%s is a class method' % name
          # TODO
        ...
    return cls

(評論太長了)

我冒昧地添加了指定哪些方法應該被裝飾到您的解決方案的能力:

def class_decorator(*method_names):

    def wrapper(cls):

        for name, meth in inspect.getmembers(cls):
            if name in method_names or len(method_names) == 0:
                if inspect.ismethod(meth):
                    if inspect.isclass(meth.im_self):
                        # meth is a classmethod
                        setattr(cls, name, VerifyTokenMethod(meth))
                    else:
                        # meth is a regular method
                        setattr(cls, name, VerifyTokenMethod(meth))
                elif inspect.isfunction(meth):
                    # meth is a staticmethod
                    setattr(cls, name, VerifyTokenMethod(meth))

        return cls

    return wrapper

用法:

@class_decorator('some_method')
class Foo(object):

    def some_method(self):
        print 'I am decorated'

    def another_method(self):
        print 'I am NOT decorated'

以上答案並不直接適用於 python3。 基於其他很好的答案,我已經能夠提出以下解決方案:

import inspect
import types
import networkx as nx


def override_methods(cls):
    for name, meth in inspect.getmembers(cls):
        if name in cls.methods_to_override:
            setattr(cls, name, cls.DecorateMethod(meth))
    return cls


@override_methods
class DiGraph(nx.DiGraph):

    methods_to_override = ("add_node", "remove_edge", "add_edge")

    class DecorateMethod:

        def __init__(self, func):
            self.func = func

        def __get__(self, obj, cls=None):
            def wrapper(*args, **kwargs):
                ret = self.func(obj, *args, **kwargs)
                obj._dirty = True  # This is the attribute I want to update
                return ret
            return wrapper

    def __init__(self):
        super().__init__()
        self._dirty = True

現在,只要調用元組methods_to_override中的方法,就會設置臟標志。 當然,其他任何東西也可以放在那里。 沒有必要在需要覆蓋其方法的 class 中包含DecorateMethod class。 但是,由於DecorateMehod使用 class 的特定屬性,我更喜歡創建 class 屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM