python - 检查参数是否在不检查值的情况下传递给函数
问题描述
我不确定这在 Python 中是否可行,我想知道,是否有任何方法可以在运行时检查参数是否传递给 Python 函数而不对参数值进行某种检查?
def my_func(req, opt=0):
return was_opt_passed() # Returns bool
print(my_func(0)) # Prints False
print(my_func(0, 0)) # Prints True
如果可能的话,这在某些情况下会更好,因为它消除了记住和检查哨兵值的需要。可能吗?
解决方案
正如马克在他的评论中已经说过的,典型的约定是使用默认值None
。然后你可以检查它是否仍然None
在调用。
def my_func(req, opt=None):
if opt is None:
#opt wasn’t passed.
return False
#opt was passed
return True
尽管如果您想对其他选项进行更多研究(大多数情况下最不合常规),请随时查看这些答案
推荐阅读
- c# - OpenSSL 中的 VC-WIN32-ONECORE 是什么意思?
- reactjs - Redux - 处理非常大的状态对象
- python - 如何让我的 if 语句在结果生成后在语句中运行代码?
- android - 是否可以在单个 Android Spannable 上添加 2 种颜色?
- javascript - 使用 jQuery 定位表行,其中包含值
- windows - 无需在启动或安装期间输入用户凭据即可启动或注册 Windows 服务
- sonarqube - 将 TeamCity 中的 DotCover 报告集成到 SonarQube 中?
- c# - 直接调用方法 - MakeGenericMethod
- javascript - 单元格表上的多个倒数计时器
- ios - Alamofire assertionFailure - needNewBodyStream 没有找到 UploadRequest