python:简单装饰函数的类命名空间

python:简单装饰函数的类命名空间,python,decorator,python-decorators,Python,Decorator,Python Decorators,我对Python中的decorators有点陌生,正在尝试使用一个简单的decorator,该decorator应该在第一次实际调用一个依赖函数时检查我的类执行操作的状态。我的问题是,我想让decorator函数也知道self中的所有内容,并将实际函数作为“参数”传递 class myClass(object): __init__(self): self.__isFoo = False self.__baz = 0 def doFoo(self)

我对Python中的decorators有点陌生,正在尝试使用一个简单的decorator,该decorator应该在第一次实际调用一个依赖函数时检查我的类执行操作的状态。我的问题是,我想让decorator函数也知道self中的所有内容,并将实际函数作为“参数”传递

class myClass(object):
    __init__(self):
        self.__isFoo = False
        self.__baz = 0

    def doFoo(self):
        ...  
        self.__isFoo = True

    def fooInit(self,func):
        if not self.__isFoo:
            self.doFoo()
        return func

    @property
    @fooInit
    def getBaz(self):
        return self.__baz
然而,对于这个,我得到了一个错误

myObj = myClass()
myObj.getBaz

~~> TypeError: fooInit() takes exactly 2 arguments (1 given)
我有点理解,因为它只是 self.fooinit self.getBaz 如果我正确理解装饰师,或者


所以我现在有点不知所措了,我如何能够以一种简单的方式定义decorator,它还知道类名称空间中的其他对象?

根据@Aruistante的建议,我设法找到了一个合适的decorator

def fooInit(func):
    def _wrapped(self,*args, **kwargs):
        if not self.__isFoo:
            self.fooInit()
            return func(self,*args, **kwargs)
    return _wrapped

在我的类中定义的

可能的重复实际上与您正在装饰一个属性有关。请参阅链接的副本。记住,装饰器的参数实际上是func、*args、**kwargs,其中args[0]是self。一般来说,它们本身并不被定义为类名称空间的一部分,而且还必须记住调用传入函数。decorator只是编写wrapperfunc、*args、**kwargs的语法糖,其中func始终是修饰函数。它们根本不会改变python的调用机制。您有一个输入错误,在初始化self之前缺少def