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

时间:2018-06-11 06:44:15

标签: python decorator python-import python-module python-decorators

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

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)

3 个答案:

答案 0 :(得分:3)

正如错误暗示的那样,你的装饰者是一种方法;尝试使它成为一个静态函数:

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

但问题是你为什么把它放在ABC

答案 1 :(得分:1)

由于装饰器未使用self,因此包装器看起来可能是静态方法。如果您声明decorate_me,则可以将其与@ABC.deocarate_me一起使用。

如果要在其他类中使用此装饰器,请考虑将具有装饰器的类作为其他类继承的基类。另一个选择是根本不把装饰器放在一个类中。

答案 2 :(得分:1)

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