通过向Python脚本发送参数来调用几个(可能是静态的)成员函数之一的一种优雅方法是什么



文件script.py中的以下代码使script.py dothisscript.py dothat成为可能(在chmod 755 script.py之后)。

import sys
class DoThisOrThat:
    @staticmethod
    def dothis():
        print "We're doing this."
    @staticmethod
    def dothat():
        print "We're doing that."
if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Error: You must specify exactly one function: dothis or dothat"
        sys.exit(1)
    if sys.argv[1] == "dothis":
        FooBar.dothis()
    elif sys.argv[1] == "dothat":
        FooBar.dothat()
    else:
        print "I don't know how to "+sys.argv[1]

这是从命令行调用两个静态成员方法之一的最优雅的方法吗?

如果方法是非成员的,则使用argparseargh的解决方案是可能的。上面代码的等价物是什么?

您可以使用getattr内置调用类(或实例)的任何方法(静态/实例/类)

假设您的Factory类是

>>> class DoThisOrThat:
    @staticmethod
    def dothis_static():
        print "We're doing this static."
    @staticmethod
    def dothat():
        print "We're doing that static."
    def dothis_instance(self):
        print "We're doing this instance."
    @classmethod
    def dothis_classmethod(cls):
        print "We're doing this class method."

那么一个可能的调用就是

>>> getattr(DoThisOrThat, 'dothis')()
We're doing this.
>>> getattr(DoThisOrThat(), 'dothis_instance')()
We're doing this instance.
>>> getattr(DoThisOrThat, 'dothis_classmethod')()
We're doing this class method.

这会将您的代码修改为

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Error: You must specify exactly one function: dothis or dothat"
        sys.exit(1)
    try:
        getattr(DoThisOrThat, sys.argv[1])()
    except AttributeError:
        print "I don't know how to " + sys.argv[1]

如果您想允许从命令行调用类的任意静态方法,您也可以使用getattr来实现这一点,当然,假设参数和方法名称匹配1:

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Error: You must specify exactly one function")
        sys.exit(1)
    try:
        getattr(DoThisOrThat, sys.argv[1])()
    except AttributeError:
        print("Error: The specified method '%s' does not exist" % sys.argv[1])
        sys.exit(1)

您可以定义一个字典来将字符串映射到函数。

>>> d = {'dothis': DoThisOrThat.dothis, 'dothat': DoThisOrThat.dothat}
>>> d['dothis']()
We're doing this.
>>> d['dothat']()
We're doing that.
if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Error: You must specify exactly one function: dothis or dothat"
        sys.exit(1)
    try:
        d[sys.argv[1]]()
    except KeyError:
        print "I don't know how to "+sys.argv[1]

最新更新