除了the answer by @Ivonet,Python中的一种常见方法是接受一个参数,并将其隐藏:class Location:
__init__(self, location):
"""location_num & location_path are mutually exclusive"""
try:
x = self.locationArray[location] #location is a num?
except TypeError:
x = self.locationDict[location] #location is a string?
可能有另一个例外。如果您想使用argparse,这可能只对两个参数起到了过度的作用,但是可以很好地伸缩:
^{pr2}$
从上到下的结果:usage: Class Bla init [-h] ( num NUM | path PATH)
bla.py: error: one of the arguments num path is required
usage: Class Bla init [-h] ( num NUM | path PATH)
bla.py: error: argument num: invalid int value: 'abc'
usage: Class Bla init [-h] ( num NUM | path PATH)
bla.py: error: argument num: not allowed with argument path
这也很酷,因为Bla(help='anything')将实际打印使用情况(并退出)。这是为了回答关于argparse的具体问题,但要清楚地说,@Ivonet有我将用于您的确切示例的答案。在