首页 > 解决方案 > 在 python 2.7 中使用另一个类的装饰

问题描述

我正在尝试从 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)

标签: pythondecoratorpython-importpython-modulepython-decorators

解决方案


正如错误所暗示的,您的装饰器是一种方法;尝试使其成为静态函数:

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

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


推荐阅读