python - 用可选参数装饰 python 方法

标签 python decorator

我有一个 Python 类,其中包含许多带签名的方法:

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

即这些方法具有不同数量 (1-3) 的位置参数,并且可选参数与默认值 False 相交。我想用一个装饰器来装饰所有这些方法,它将检查 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 功能。有什么建议吗?

乔金姆

最佳答案

我假设 intersect 将始终作为关键字参数传递。在这种情况下,您可以简单地在装饰器内执行此操作

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  

关于python - 用可选参数装饰 python 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9565853/

相关文章:

python - 缩放 matplotlib 图,以便显示小/大正/负差异

angularjs - 在 Jasmine 测试中模拟 AngularJS $httpBackend 并使用装饰器时出现 "$httpBackend.when is not a function"错误

typescript - 如何限制给定参数装饰器可以应用于的参数类型

python - 如何在 Django 中创建装饰器来装饰 View

python - python中的函数装饰器是否隐式调用被装饰的函数?

python - 此代码中的 `return result` 是否会影响此装饰器的结果?

python - 用户定义的函数不适用于 Pandas

python - 在python中访问超(父)类变量

python - 如何从 nltk 分类器中获取精度和召回率?

python - 如何在pytest中进行依赖参数化?