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) 如果我理解正确的装饰,还是?
所以我现在有点迷路了,我怎样才能以简单的方式定义装饰器,它也知道类命名空间中的其他对象?
可能重复://计算器.com/questions/4923706/decorating-a-class-method-after-property) – aruisdante 2014-10-17 15:45:09
这实际上与你装饰物业的事实有关。查看链接的副本。 – aruisdante 2014-10-17 15:45:28
并且记住,你对装饰器的参数实际上是''(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