【问题标题】:Using a decorator inside the class and call the object在类中使用装饰器并调用对象
【发布时间】:2019-02-09 03:34:54
【问题描述】:

我有一个类,其中有一个名为decorator_func 的函数和另一个名为name_me 的函数。如何用类中的其他函数装饰name_me 函数?

这是我目前尝试过的:

class Test :
    
    def decorator_func(fun):
        def disp_fun(name):
            return ("hello there ,") + fun(name)
        return disp_fun
@decorator_func
def name_me(name):
      return name
    
print name_me("abhi")

obj = Test()
obj.decorator_func()

The description of the code is mentioned in the image given below . Anaconda jyupiter lab is used to execute the code

如何消除此错误?

【问题讨论】:

    标签: python oop python-decorators


    【解决方案1】:

    您的代码的问题在于,您使用 Test 类中的方法装饰了 name_me 函数。

    您可以从Test 类中移动decorator_func,然后您的代码将如下所示:

    def decorator_func(fun):
        def disp_fun(name):
            return ("hello there, ") + fun(name)
        return disp_fun
    
    @decorator_func
    def name_me(name):
      return name
    
    print name_me("abhi")
    

    我们创建Test 类的实例,并用实例的方法装饰name_me 函数,如下所示:

    class Test :
        def decorator_func(self, fun):
            def disp_fun(name):
                return ("hello there, ") + fun(name)
            return disp_fun
    
    # Create a instance of the Test class
    obj = Test()
    
    @obj.decorator_func
    def name_me(name):
        return name
    
    print name_me("abhi")
    

    【讨论】:

      猜你喜欢
      • 2019-03-17
      • 2021-09-29
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-12
      相关资源
      最近更新 更多