如何使具有互斥参数的Python函数? [英] How do I make a Python function with mutually exclusive arguments?
问题描述
我有一个Python类,它需要接受两个互斥参数之一.如果参数不是互斥的(即,如果两个或两个都不给出),则将引发错误.
I have a Python class which needs to accept one of two mutually exclusive arguments. If the arguments are not exclusive, (ie: if both or neither are given), an error should be raised.
class OrgLocation:
__init__(self, location_num=None, location_path=None):
"""location_num & location_path are mutually exclusive"""
在大多数情况下,最好的选择是制作两个单独的类.但是,我正在使用外部API ,该API 需要这两个属性是互斥的.
In most scenarios, the best option would be to make two separate classes. However, I am working with an external API which requires these two attributes to be mutually exclusive.
请求:
<OrgLocation LocationPathName="ROOT/BU/DIV/SL/DEPT/JOB" LocationNum="1234"/>
响应:
<Error Message="Use either LocationNum or LocationPathName but not both." ErrorCode="1186">
类似的问题似乎表明 argparse
可以用于命令行界面中的互斥参数,但是我不确定如何将其应用于类构造器
Similar questions seem to indicate that argparse
can be used for mutually exclusive arguments in command-line interfaces, but I'm unsure how to apply this to a class constructor
如何创建带有互斥参数的Python函数?
How can I create a Python function with mutually exclusive arguments?
推荐答案
您可能想在 init 方法中创建测试,但更好的问题可能是...为什么?
You might want to create a test in the init method but a better question might be... Why?
if location_num is not None and location_path is not None:
raise TheseParametersAreMutuallyExclusiveError()
您为什么要创建一个有多重目的的课程?为什么不创建单独的类?
Why would you make a class that has multiple purposes? Why not create separate classes?
这篇关于如何使具有互斥参数的Python函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!