从两个选择中选择一个强制性参数的Python

从两个选择中选择一个强制性参数的Python

本文介绍了从两个选择中选择一个强制性参数的Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能:

def delete(title=None, pageid=None):
    # Deletes the page given, either by its title or ID
    ...
    pass

但是,我的意图是让函数仅接受一个参数(titlepageid).例如,delete(title="MyPage")delete(pageid=53342)有效,而delete(title="MyPage", pageid=53342)无效.不能传递零参数.我将如何去做?

However, my intention is for the function to take only one argument (either title OR pageid). For example, delete(title="MyPage") or delete(pageid=53342) are valid, while delete(title="MyPage", pageid=53342), is not. Zero arguments can not be passed. How would I go about doing this?

推荐答案

没有Python语法可让您定义异或参数,否.您必须明确地引发一个例外,即是否同时指定了两个或全部未指定:

There is no Python syntax that'll let you define exclusive-or arguments, no. You'd have to explicitly raise an exception is both or none are specified:

if (title and pageid) or not (title or pageid):
    raise ValueError('Can only delete by title OR pageid')

这篇关于从两个选择中选择一个强制性参数的Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:10