简体   繁体   English

类内的python-Decorator函数

[英]python-Decorator function inside Class

I have the below code which works fine if I remove self from methods 我有以下代码,如果我将自己从方法中删除,则可以正常工作

class tests:
    def __init__(self):
        pass
    def func(self,a):
        def wrapp(x):
            y=x+2
            return a(y)
        return wrapp
    @func
    def func1(self,b):
        return b

print (tests.func1(10))

I believe decorator function are functions that return another function. 我相信装饰器函数是返回另一个函数的函数。 Will that not work inside class? 那在课堂上行不通吗? Ignore the indentation error as I am not achievable when I paste the code here.. Please help me how I can achieve this scenario inside class.. 忽略缩进错误,因为在将代码粘贴到此处时无法实现。请帮助我如何在课堂中实现此方案。

You can just declare your decorator outside of the class. 您可以在类之外声明装饰器。 Also, when you are decorating a class method, it seems you need to pass the self variable from the wrapper to the decorated function (changed the names for more clarity): 同样,当装饰一个类方法时,似乎需要将自变量从包装器传递给装饰的函数(为了更清晰起见,更改了名称):

def add_two(fn):
    def wrapper(self, x):
        y = x + 2
        return fn(self, y) 
    return wrapper

class Test:
    @add_two
    def func1(self, b):
        return b

f = Test()
f.func1(5) # returns 7

This issue here isn't the decorator at all. 这里的问题根本不是装饰器。 This issue is you are using func1 and your decorator as static methods without removing the self argument. 此问题是您将func1和装饰器用作静态方法,而没有删除self参数。 If you remove the self arguments this will work fine. 如果删除自变量,则可以正常工作。

Without staticmethod decorator 没有staticmethod装饰器

class Test:
    def add_two(func=None):
        def wrapper_add_two(*args, **kwargs):
            return func(*args, **kwargs) + 2
        return wrapper_add_two

    @add_two
    def func1(b):
        return b

print(Test.func1(10)) #12

With staticmethod decorator 带有staticmethod装饰器

Unfortunately using them in this manner stores them as unbound static methods and you need to bind them for this to work properly. 不幸的是,以这种方式使用它们将它们存储为未绑定的静态方法,并且您需要绑定它们才能使其正常工作。

class Test:
    @staticmethod
    def add_two(func):
        def wrapper_add_two(*args, **kwargs):
            return func.__func__(*args, **kwargs) + 2
        return wrapper_add_two

    @add_two.__func__
    @staticmethod
    def func1(b):
        return b

print(Test.func1(10)) #12

Running with the staticmethod decorator and without the function binding gives you 使用staticmethod装饰器运行并且没有函数绑定可以为您提供

TypeError: 'staticmethod' object is not callable TypeError:“静态方法”对象不可调用

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

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