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

在python 2.7中使用另一个类中的装饰,python,decorator,python-import,python-module,python-decorators,Python,Decorator,Python Import,Python Module,Python Decorators,我试图从python中的另一个类调用装饰器。下面是代码 文件_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"

我试图从python中的另一个类调用装饰器。下面是代码

文件_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
from file_1 import ABC
@ABC.decorate_me
def test():
    print "In test function ."

test()
文件_2.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
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

正如错误所暗示的,你的装饰者是一种方法;尝试将其设置为静态函数:

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

但问题是,为什么要将它放在
ABC

既然装饰程序没有使用
self
,那么包装器可能是一种静态方法。如果您声明
decoration\u me
,您可以将其与
@ABC.deocarate\u me
一起使用


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

因为decorator没有使用
self
,所以包装器可能是一个静态方法。如果您声明
decoration\u me
,您可以将其与
@ABC.deocarate\u me
一起使用


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

文件\u 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

请在
文件_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

我想在很多类中使用这个装饰器。这就是为什么我会把它放在公共类中,我想在很多类中使用这个装饰器。这就是我将它放在公共类中的原因。在这种情况下,不是
classmethod
,而是
staticmethod
:类方法仍然需要类。在这种情况下,不是
classmethod
,而是
staticmethod
:类方法仍然需要类。