【问题标题】:Binding command line arguments to the object methods calls in Python将命令行参数绑定到 Python 中的对象方法调用
【发布时间】:2016-12-28 01:30:20
【问题描述】:

我正在开发一个带有一些可能参数的命令行实用程序。参数解析是使用 argparse 模块完成的。最后,通过一些额外的定制,我得到了一个只有一个元素的字典:

{'add_account': ['example.com', 'example']}

其中键是应转换为方法调用的选项,值是参数列表。 我已经实现了所有计划对象方法。 我想知道基于接收到的字典创建方法调用的最好、最 Pythonic 的方法是什么。 我显然可以通过一个预定义的映射,如:

if option == 'add_account':
    object.add_account(
                       dictionary['add_account'][0],
                       dictionary['add_account'][1]
                       )

不过,我觉得有更好的方法可以做到这一点。

【问题讨论】:

  • 制作add_account 接受列表,然后传递dictionary['add_account']
  • 或者让它保留,然后使用*dictionary['add_account']。

标签: python-3.x argparse


【解决方案1】:

您可以使用getattr 获取方法对象(argparse.py 多次使用此方法)。

你没有给我们一个具体的例子,但我猜你有一个这样的类:

In [387]: class MyClass(object):
     ...:     def add_account(self,*args):
     ...:         print(args)
     ...:         
In [388]: obj=MyClass()
In [389]: obj.add_account(*['one','two'])
('one', 'two')

做同样的事情,从一个字符串开始,我可以使用getattr来获取方法对象:

In [390]: getattr(obj,'add_account')
Out[390]: <bound method MyClass.add_account of <__main__.MyClass object at 0x98ddaf2c>>
In [391]: getattr(obj,'add_account')('one')
('one',)

现在用你的字典:

In [392]: dd={'add_account': ['example.com', 'example']}
In [393]: key='add_account'
In [394]: getattr(obj, key)(*dd[key])
('example.com', 'example')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    相关资源
    最近更新 更多