在 python 2.7 中使用另一个 class 的装饰

Using decorate from another class in python 2.7

我正在尝试从 python 中的另一个 class 调用装饰器。下面是代码

file_1.py

class ABC:
    def decorate_me(func):
        def wrapper():
            print "Hello I am in decorate_me func"
            print "Calling decorator function"
            func()
            print "After decorator"
        return wrapper

file_2.py

from file_1 import ABC
@ABC.decorate_me
def test():
    print "In test function ."

test()

输出

TypeError: unbound method decorate_me() must be called with ABC instance as first argument (got function instance instead)

正如错误提示的那样,您的装饰器是一种方法;尝试将其设为静态函数:

class ABC:
    @staticmethod
    def decorate_me(func):
        ...

但问题是为什么要放在ABC中?

因为你的装饰器没有使用 self 看起来包装器可能是一个静态方法。如果您这样声明 decorate_me,您可以将它与 @ABC.deocarate_me.

一起使用

如果您想在其他 classes 中使用此装饰器,请考虑将带有装饰器的 class 作为其他 classes 继承的基础 class从。另一种选择是根本不将装饰器放在 class 中。

file_2.py 中尝试以下代码:

from file_1 import ABC
dec = ABC.decorate_me
@dec
def test():
    print("In test function .")

test()

输出:

Hello I am in decorate_me func
Calling decorator function
In test function .
After decorator