odoo17的(NewId)创建新记录的伪标识符对象如何实现

Pseudo-ids for new records, encapsulating an optional origin id (actual record id) and an optional reference (any value).

class NewId(object):

    """ Pseudo-ids for new records, encapsulating an optional origin id (actual

        record id) and an optional reference (any value).

    """

    __slots__ = ['origin', 'ref']


    def __init__(self, origin=None, ref=None):

        self.origin = origin

        self.ref = ref


    def __bool__(self):

        return False


    def __eq__(self, other):

        return isinstance(other, NewId) and (

            (self.origin and other.origin and self.origin == other.origin)

            or (self.ref and other.ref and self.ref == other.ref)

        )


    def __hash__(self):

        return hash(self.origin or self.ref or id(self))


    def __repr__(self):

        return (

            "<NewId origin=%r>" % self.origin if self.origin else

            "<NewId ref=%r>" % self.ref if self.ref else

            "<NewId 0x%x>" % id(self)

        )


    def __str__(self):

        if self.origin or self.ref:

            id_part = repr(self.origin or self.ref)

        else:

            id_part = hex(id(self))

        return "NewId_%s" % id_part 

这段代码定义了一个名为 `NewId` 的类,用于表示新记录的伪标识符。让我简要解释一下:


- `__init__(self, origin=None, ref=None)` 方法用于初始化对象,接受两个可选参数 `origin` 和 `ref`,分别表示原始记录的标识符和参考值。

- `__bool__(self)` 方法返回 `False`,表示该对象的布尔值为假。

- `__eq__(self, other)` 方法用于比较两个 `NewId` 对象是否相等。它首先检查另一个对象是否也是 `NewId` 类的实例,然后比较它们的 `origin` 或 `ref` 属性是否相等。

- `__hash__(self)` 方法返回对象的哈希值,用于在集合中进行哈希查找。

- `__repr__(self)` 方法返回对象的字符串表示形式,根据是否存在 `origin` 或 `ref` 属性,分别返回不同的格式化字符串。

- `__str__(self)` 方法返回对象的字符串表示形式,根据是否存在 `origin` 或 `ref` 属性,返回相应的标识符字符串。


总的来说,这个类用于创建表示新记录的伪标识符对象,可以包含原始记录的标识符或任何参考值。

广州众谛信息科技有限公司, Odoo小老谛 2024年3月30日
分析这篇文章
标签
存档
登录 留下评论
什么是ERP
企业资源企划