python - 如果传递了另一个参数,则 Python 函数使参数成为强制性参数
问题描述
我在 Python 中有一个函数作为
def myfunc(a, b=None, c=None):
my code here
有没有办法确保如果用户传递参数的值,b
则必须将参数传递c
给myfunc
?
解决方案
您可以在函数中编写一个简单的if
条件。请看下面的代码:
def myfunc(a, b=None, c=None):
if c is not None and b is None:
raise ValueError("Value of b must be passed if value of c is passed")
your code here
推荐阅读
- c# - 为什么在尝试验证令牌时得到 401
- jquery - 使用 after() 在标题中我的徽标之后添加一些文本,但每次用户转到另一个页面时,文本都会加载一次
- sql - 如何恢复 Big Query 中已删除的行?
- html - Firefox UI 行“故障”
- vue.js - 对于 v-for 循环中的每个结果,如何使用第一个循环结果中的参数嵌套另一个 v-for 循环
- pandas - 如何根据索引从另一个df获取列的值?熊猫
- reactjs - 我如何让 formik 在点击时更新输入?
- php - 如何在json db结构中的数组上组合whereJsonContains和orWhere
- javascript - 提交表单时出现错误无法 POST /public/register-controller
- sql - BigQuery - 在 where 和 in 子句中删除两列