我在读取 python requests 库中的 models.py 文件时发现了一个奇怪的函数调用。我尝试在 python 官方文档中找到一些解释,但不幸的是没有成功。您可能知道为什么会出现这种情况或者如何在函数调用中使用逻辑运算符吗?这些是良好实践的一部分吗?请找到下面的代码。
fields = to_key_val_list(data or {})
files = to_key_val_list(files or {})
最佳答案
这种东西在Python编程语言中经常使用
fields = to_key_val_list(data or {}) # this means, that if boolean value of data variable is False, use empty dict/or anything you want.
还有,,,
class Foo:
def __init__(self, data: list):
self.data = data or 'abc' # if data will be empty list self.data will become 'abc'
您也可以使用 and 。和/或两者都可用。
val = a or b or c # in the chain, if a is False, value of val would become b. if be is False also, then c
val = a and b and c # "and" checks values of whole chain. if a is False, so val will have same value as a. if all is true in chain, the last element value will be inside val.
关于python - 是否可以使用逻辑语句作为参数来调用python函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56216083/