2014-01-10 71 views
0

我有一个类,让所谓的WindCMD,它与装饰功能如何获得函数的装饰器?

@options( 
      [ 
       make_option('-s', '--windspeed', 
          default = 999, 
          help = "Set the wind speed." 
          ), 

       make_option('-d', '--winddir', 
          default = 999, 
          help = "Set the wind direction." 
          )        
       ] 
      )  
def do_set_wind_manually(self, line, opts = None): 

有一种可能性,通过使用__dict__获得类的所有功能,但我怎么能得到的功能装饰和选择?

回答

2

你不能一般。装饰器只是对函数执行预处理步骤。装饰器返回的对象可能不是你定义的原始函数(并且在大多数情况下,它包装了一个它不是的函数)。一旦一个装饰器完成了它的工作,在返回的函数中就没有记录留下的记录,这是记录在其他函数上的装饰器的结果。你可能定义一个装饰器,它在函数上设置一些属性。例如:

class options(object): 
    def __init__(self, somearg): 
     self.somearg = somearg 

    def __call__(self, func): 
     func.options = self 
     return func 

>>> @options('foo') 
... def myfunc(): pass 
... 
>>> myfunc.options 
... <__main__.options at 0x19f6d90> 
>>> myfunc.options.somearg 
... 'foo' 

我想如果你真的需要你,也可以写一个装饰器来包装装饰器并记录它们。这只是一个粗略的实现,它的想法:

class record_decorator(object): 
    def __init__(self, decorator): 
     self.decorator = decorator 

    def __call__(self, func): 
     result = self.decorator(func) 
     if not hasattr(result, 'decorators'): 
      if hasattr(func, 'decorators'): 
       result.decorators = func.decorators[:] # copy 
      else: 
       result.decorators = [] 
     result.decorators.append(self.decorator) 
     return result 

>>> def a(func): 
...  print 'decorating with a' 
...  return func 
... 
>>> def a(func): 
...  print 'decorating with a' 
...  return func 
... 
>>> @record_decorator(b) 
... @record_decorator(a) 
... def myfunc(): pass 
... 
decorating with a 
decorating with b 
>>> myfunc.decorators 
[<function __main__.a>, <function __main__.b>] 

现在myfunc.decorators包含适用于功能,他们应用的顺序所有装饰的列表。至少在原则上 - 它仍然不会告诉你任何使用而没有的装饰者使用record_decorator