Ste*_*ica 7 python arguments mutual-exclusion
我有一个 Python 类,它需要接受两个互斥参数之一。如果参数不是排他性的(即:如果两者都给出或都不给出),则应引发错误。
class OrgLocation:
__init__(self, location_num=None, location_path=None):
"""location_num & location_path are mutually exclusive"""
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,最好的选择是创建两个单独的类。但是,我正在使用一个外部 API,它要求这两个属性相互排斥。
要求:
<OrgLocation LocationPathName="ROOT/BU/DIV/SL/DEPT/JOB" LocationNum="1234"/>
Run Code Online (Sandbox Code Playgroud)
回复:
<Error Message="Use either LocationNum or LocationPathName but not both." ErrorCode="1186">
Run Code Online (Sandbox Code Playgroud)
类似的问题似乎表明argparse可用于命令行界面中的互斥参数,但我不确定如何将其应用于类构造函数
如何创建具有互斥参数的 Python 函数?
您可能想在init方法中创建一个测试,但更好的问题可能是...为什么?
if location_num is not None and location_path is not None:
raise TheseParametersAreMutuallyExclusiveError()
Run Code Online (Sandbox Code Playgroud)
为什么要创建一个具有多种用途的类?为什么不创建单独的类?