问题描述
有时候在我的代码中,我有一个函数可以用两种方式之一作为参数.像这样:
Sometimes in my code I have a function which can take an argument in one of two ways. Something like:
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可以通过以下三种方式之一出现怎么办?如果类型不同,我可以这样做:
Is there any more elegant way to do this? What if the arg could come in one of three ways? If the types are distinct I could do:
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))
但是如果不是的话该怎么办?这种选择似乎很愚蠢:
But what if they are not? This alternative seems silly:
def func(objnameOrType, isName=True):
if isName:
getObjByName(objnameOrType)
else:
getObjByType(objnameOrType)
这是因为您必须像 func(mytype,isName = False)
这样称呼它,这很奇怪.
cause then you have to call it like func(mytype, isName=False)
which is weird.
推荐答案
如何使用类似命令分发模式的内容:
How about using something like a command dispatch pattern:
def funct(objnameOrType):
dispatcher = {str: getObjByName,
type1: getObjByType1,
type2: getObjByType2}
t = type(objnameOrType)
obj = dispatcher[t](objnameOrType)
doStuffWithObj(obj)
其中 type1
, type2
等是实际的python类型(例如int,float等).
where type1
,type2
, etc are actual python types (e.g. int, float, etc).
这篇关于互斥关键字args的优雅模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!