2014-10-17 30 views
0

我对Python中的装饰器有些新鲜,并且正在用一个简单的装饰器来构造,这应该会检查我的类的状态(当一个依赖函数是实际上是第一次要求)。我的问题是,我想让装饰功能也了解一下自己的一切,并通过实际的功能为“参数”(?)python:简单的装饰器函数的类名称空间

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) 如果我理解正确的装饰,还是?

所以我现在有点迷路了,我怎样才能以简单的方式定义装饰器,它也知道类命名空间中的其他对象?

+2

可能重复://计算器.com/questions/4923706/decorating-a-class-method-after-property) – aruisdante 2014-10-17 15:45:09

+0

这实际上与你装饰物业的事实有关。查看链接的副本。 – aruisdante 2014-10-17 15:45:28

+1

并且记住,你对装饰器的参数实际上是''(func,* args,** kwargs)'',其中''args [0]''将会是'self''。一般来说,[装饰器函数](http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/)本身没有被定义为类名称空间的一部分。 – aruisdante 2014-10-17 15:47:34

回答

0

以下@ aruisdante的建议,我得到了一个适当的装饰工作

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

(我的类中定义)装饰一类方法@property后(HTTP的