Skip to main content
 首页 » 编程设计

python之检查参数是否在不检查值的情况下传递给函数

2024年11月01日9dflying

我不确定这在 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 

如果可能的话,这在某些情况下会更好,因为它减轻了记住和检查标记值的需要。可能吗?

请您参考如下方法:

检测参数是否已传递的标准方法是标记值;但是,如果您愿意丢失函数签名,则可以使用 **kwargs:

def my_func(**kwargs): 
  return 'opt' in kwargs 
print(my_func()) #=> False 
print(my_func(opt=0)) $=> True