Python 在类中使用装饰器并调用对象

Python 在类中使用装饰器并调用对象,python,oop,python-decorators,Python,Oop,Python Decorators,我有一个类,其函数名为decorator\u func,另一个函数名为name\u me。如何用类中的其他函数装饰name\u me函数 以下是我迄今为止所做的尝试: 类测试: def decorator_func(乐趣): def disp_fun(名称): return(“你好,”)+fun(姓名) 返回disp_fun @装饰师 def名称(名称): 返回名称 打印姓名(“abhi”) obj=测试() obj.decorator_func()代码的问题是,您使用Test类中的方法装饰n

我有一个类,其函数名为
decorator\u func
,另一个函数名为
name\u me
。如何用类中的其他函数装饰
name\u me
函数

以下是我迄今为止所做的尝试:

类测试:
def decorator_func(乐趣):
def disp_fun(名称):
return(“你好,”)+fun(姓名)
返回disp_fun
@装饰师
def名称(名称):
返回名称
打印姓名(“abhi”)
obj=测试()

obj.decorator_func()
代码的问题是,您使用
Test
类中的方法装饰
name_me
函数

您可以从
Test
类中移动
decorator\u 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")
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")
我们的任务是创建
Test
类的实例,并用实例的方法装饰
name\u me
函数,如下所示:

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")
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")

代码的问题是,您使用
Test
类中的方法装饰
name\u me
函数

您可以从
Test
类中移动
decorator\u 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")
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")
我们的任务是创建
Test
类的实例,并用实例的方法装饰
name\u me
函数,如下所示:

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")
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")