为什么有些运算符在 Odoo 中无法按预期处理记录集?

Why some operators are not working as expected with recordsets in Odoo?

我做了一些测试:

>>> empty_recordset = self.env['res.users']                                 # empty recordset
>>> not_empty_recordset = self.env['res.users'].search([('id', '=', 1)])    # recordset with one record

>>> empty_recordset is False
False

>>> empty_recordset is None
False

>>> empty_recordset == False
False

>>> empty_recordset == True
False

>>> bool(empty_recordset)
False

>>> not empty_recordset
True

>>> if empty_recordset:           # it is treated as False
...     print('hello')
... 

>>> bool(not_empty_recordset)
True

>>> if not_empty_recordset:
...     print('hello')
... 
hello

>>> not not_empty_recordset
False

这是怎么回事?记录集是否仅通过 ifnot 语句被视为布尔值?其余的运算符没有超载吗?

这是__nonzero__的实现方式:

Called to implement truth value testing and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. When this method is not defined, len() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither len() nor nonzero(), all its instances are considered true.

您可以在odoo/odoo/models.py上查看:

对于 Odoo 10,代码是:

def __nonzero__(self):
    """ Test whether ``self`` is nonempty. """
    return bool(getattr(self, '_ids', True))

除了卢卡斯的回答,说明一切。在 python 中所有操作都转换为方法调用

      if object: 
       #  is turned to. 
      if object.__nonzero__():

      if object == value:
      #is turned to
      if object.__eq__(value):

即使这样也是:

      object + value
      # is converted go this
      object.__add__(value) 

所有算子都有匹配的方法

这就是为什么在更改运算符时得到不同结果的原因,因为 python 在后台调用了不同的方法。