小编vol*_*ano的帖子

带有位置参数的函数的装饰器,带有通用命名参数

我有一组函数/方法,它们都有不同的位置参数集,在某些情况下还有关键字参数,但共享一个名为Lane_type 的字符串参数。它可以是位置参数或关键字参数。由于设计缺陷(有罪),不同地方的相同值在字符串中可能有大写字母。因此,为了进行比较,我必须将其转换为小写。最终我决定尝试通过装饰器进行转换:

def lt_dec(func):
    def _lt_lower(**kwargs):
        kwargs['lane_type'] = kwargs['lane_type'].lower()
        return func(**kwargs)
    return _lt_lower
Run Code Online (Sandbox Code Playgroud)

当然,我试图测试它 - 它失败了:

In [38]: @lt_dec
def test1(lane_type):
    print lane_type
   ....:     

In [39]: test1('Solid')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/homes/markg/<ipython-input-39-bb6cef5c7fad> in <module>()
----> 1 test1('Solid')

TypeError: _lt_lower() takes exactly 0 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)

显然,我并不完全了解 **kwargs 替换机制。我将非常感谢我所缺少的解释以及我的问题是否有优雅的解决方案。

编辑:

我相信为了清楚起见,我应该展示一些函数定义的例子:这是一个类中的方法

def add_polygon(self, points, lane_type, color):
Run Code Online (Sandbox Code Playgroud)

另一个类的方法:

def __init__(self, points, lane_type, color, side=None):
Run Code Online (Sandbox Code Playgroud)

一个函数

def lane_weight(lane_type):
Run Code Online (Sandbox Code Playgroud)

当然,对于具有 1 个参数的函数(我有几个),解决方案很简单

def lt_dec(func):
    def _lt_lower(lane_type):
        return func(lane_type)
    return …
Run Code Online (Sandbox Code Playgroud)

python decorator keyword-argument python-2.7

4
推荐指数
1
解决办法
3902
查看次数

Python 中的参数依赖项 - 无法使其工作

我正在尝试向我的脚本添加参数依赖项。这个想法是--clone参数将需要非空--gituser

仔细阅读这个例子后,我尝试了以下

In [93]: class CloneAction(argparse.Action):
    ...:     def __call__(self, parser, namespace, _):
    ...:         if not namespace.git_user and namespace.clone:
    ...:             parser.error('"--clone" requires legal git user')
    ...:             
In [94]: parser = argparse.ArgumentParser()

In [95]: parser.add_argument('-g', '--gituser', dest='git_user', type=str, default='', action=CloneAction)
Out[95]: CloneAction(option_strings=['-g', '--gituser'], dest='git_user', nargs=None, const=None, default='', type=<type 'str'>, choices=None, help=None, metavar=None)

In [96]: parser.add_argument('--clone', action='store_true', default=False)
Out[96]: _StoreTrueAction(option_strings=['--clone'], dest='clone', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
Run Code Online (Sandbox Code Playgroud)

唉,它没有用

In [97]: parser.parse_args(['--clone'])
Out[97]: Namespace(clone=True, git_user='')
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

python argparse

3
推荐指数
1
解决办法
807
查看次数