用可选参数装饰python方法

时间:2012-03-05 11:28:13

标签: python decorator

我有一个带有签名的许多方法的Python类:

def select_xxx(self, arg1 , arg2 , .. argn, intersect = False)

即。方法具有变化的(1-3)位置参数,可选参数与默认值False相交。我想用一个decorater来装饰所有这些方法,这个decorater会不考虑intersect参数的值并相应地采取不同的操作。我目前的做法是这样的:

def select_decorator(select_method):

  def select_wrapper( self , *args, intersect = False , **kwargs)
     if intersect:
        # Special init code for intersect == True
        select_method( self , *args , **kwargs)
     else:
        # Normal call path for intersect == False 
        select_method( self , *args , **kwargs)

  return select_wrapper  

@select_decorator
select_xxx( self , arg1 , arg2 , intersect = False)

但是将可选参数交叉到装饰器内的* args和** kwargs混合当前并不令人高兴。我可以牺牲** kwargs功能,如果这使问题更容易解决。有什么建议吗?

乔金姆

1 个答案:

答案 0 :(得分:2)

我假设cross总是作为关键字参数传递。在这种情况下,您可以在装饰器内完成此操作

def select_decorator(select_method):

  def select_wrapper( self , *args, **kwargs):
     intersect = kwargs.has_key('intersect') and kwargs['intersect']
     if intersect:
        # Special init code for intersect == True
        select_method( self , *args , **kwargs)
     else:
        # Normal call path for intersect == False 
        select_method( self , *args , **kwargs)
  return select_wrapper