gpt4 book ai didi

python - 为什么这个 python 表达式参数在调用时没有扩展?

转载 作者:太空狗 更新时间:2023-10-29 21:10:36 24 4
gpt4 key购买 nike

在 google appengine NDB there are queries像这样:

query = Account.query(Account.userid >= 40)

为什么 Account.userid >= 40 表达式在作为参数传递之前没有在调用时扩展为 true 或 false?过滤器表达式如何传递给查询?是用运算符重载完成的吗?

最佳答案

Ignacio 是正确的,NDB 代码在其 Property class 上定义自定义魔术方法用于比较检查。这些函数(__eq____ne____lt__等)都在调用this custom _comparison function在幕后。

def _comparison(self, op, value):
"""Internal helper for comparison operators.
Args:
op: The operator ('=', '<' etc.).
Returns:
A FilterNode instance representing the requested comparison.
"""
# NOTE: This is also used by query.gql().
if not self._indexed:
raise datastore_errors.BadFilterError(
'Cannot query for unindexed property %s' % self._name)
from .query import FilterNode # Import late to avoid circular imports.
if value is not None:
value = self._do_validate(value)
value = self._call_to_base_type(value)
value = self._datastore_type(value)
return FilterNode(self._name, op, value)

如您所见,代码不返回 bool 结果,它返回 FilterNode 的实例,该实例本身评估为适合比较的 truthy/falsey 值。

How come the Account.userid >= 40 expression is not expanded at call time to true or false before passed as an argument?

从技术上讲,它在 query() 函数被调用之前得到扩展/求值,它只是没有求值为 bool 值。

关于python - 为什么这个 python 表达式参数在调用时没有扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47203845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com