【问题标题】:Using decorate from another class in python 2.7在 python 2.7 中使用另一个类的装饰
【发布时间】:2018-06-11 06:44:15
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 我想在多个类中使用这个装饰器。这就是我将它放在普通类中的原因
    【解决方案2】:

    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
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 在这种情况下不是classmethod,而是staticmethod:类方法仍然需要类。
      猜你喜欢
      • 2014-05-31
      • 2021-12-26
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 2017-11-16
      相关资源
      最近更新 更多