简体   繁体   English

在类内部使用装饰器并调用对象

[英]Using a decorator inside the class and call the object

I have a class with a function called decorator_func and another function called name_me . 我有一个带有名为decorator_func的函数和另一个名为name_me函数的name_me How do I decorate the name_me function with the other function from the class? 如何用类中的另一个函数修饰name_me函数?

Here is what I tried so far: 这是我到目前为止尝试过的:

 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 Anaconda jyupiter实验室用于执行代码

How to Remove this error? 如何清除此错误?

The problem with your code is, that you decorate the name_me function with a method from the Test class. 代码的问题是,您用Test类中的方法装饰了name_me函数。

You can either move the decorator_func from the Test class, then your code would look like this: 您可以从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")

Our you create an instance of the Test class and decorate the name_me function with the method of the instance, like this: 我们创建一个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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM