如何使用互斥参数创建 Python 函数? [英] How do I make a Python function with mutually exclusive arguments?

查看:24
本文介绍了如何使用互斥参数创建 Python 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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,它要求这两个属性相互排斥.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆