python - 互斥关键字参数的优雅模式?

标签 python design-patterns coding-style

有时在我的代码中,我有一个函数可以通过两种方式之一接受参数。像这样的东西:

def func(objname=None, objtype=None):
    if objname is not None and objtype is not None:
        raise ValueError("only 1 of the ways at a time")
    if objname is not None:
        obj = getObjByName(objname)
    elif objtype is not None:
        obj = getObjByType(objtype)
    else:
        raise ValueError("not given any of the ways")

    doStuffWithObj(obj)

有没有更优雅的方法来做到这一点?如果 arg 可以通过三种方式之一出现怎么办?如果类型不同,我可以这样做:

def func(objnameOrType):
    if type(objnameOrType) is str:
        getObjByName(objnameOrType)
    elif type(objnameOrType) is type:
        getObjByType(objnameOrType)
    else:
        raise ValueError("unk arg type: %s" % type(objnameOrType))

但如果他们不是呢?这个替代方案看起来很愚蠢:

def func(objnameOrType, isName=True):
    if isName:
        getObjByName(objnameOrType)
    else:
        getObjByType(objnameOrType)

因为你必须像 func(mytype, isName=False) 那样调用它,这很奇怪。

最佳答案

如何使用类似命令调度模式的东西:

def funct(objnameOrType):
   dispatcher = {str: getObjByName,
                 type1: getObjByType1,
                 type2: getObjByType2}
   t = type(objnameOrType)
   obj = dispatcher[t](objnameOrType)
   doStuffWithObj(obj)

其中 type1type2 等是实际的 Python 类型(例如 int、float 等)。

关于python - 互斥关键字参数的优雅模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5184382/

相关文章:

python - 将视频保存为帧 OpenCV{PY}

python - Azure Flask 部署 - WSGI 接口(interface)

java - 如何在 Spring Boot 中将属性设置为通用 @Service 类?

mysql - 我是否在我的 SQL 语句中运行了太多子查询?

java - 一个对象的两个接口(interface)的命名约定

python - 将 Python pandas 数据帧行切片写入文件

python - 使用pymssql时如何传递连接参数 "ApplicationIntent=ReadOnly"

design-patterns - 在 laravel 5 中使用设计模式

ruby - 何时使用在 Ruby 中启动子进程的每种方法

python - Python中的长导入