禁止在数据类成员上调用的方法

Inhibiting a method called on a dataclass member

我的数据类有一个字段,其中包含一个自定义类型的数据数组(实际上它是一个 PyROOT std 向量)。但是,对于用户来说,它应该作为列表显示。使用数据类 getter 和 setter 就足够简单了,它们可以将向量转换为列表,反之亦然。但是,这仅在用户使用完整列表初始化字段时有效。如果用户想要附加到列表,显然,它不起作用,因为没有与该字段关联的永久列表。

我想知道是否有办法抑制字段上的“.append()”调用并改为调用向量的 push_back()?或者也许有一个很好的 Pythonic 方法来处理它?

上下文是,我需要 PyROOT 格式的数据类字段,因为稍后我将数据存储在 ROOT TTrees 中。但是,我正在创建此接口,以便用户无需知道 ROOT 即可使用数据类。我知道我可以创建包含相同数据的向量和列表,但这似乎是一种内存浪费,而且我不确定每次修改列表时如何更新向量。

根据 Python 文档,“Lists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application).”(强调)

考虑到这一点,我会从这样的事情开始:

from collections.abc import MutableSequence


class ListLike(MutableSequence):
    def __init__(self):
        self.backing_data = object()  # Replace with the type your using


ListLike()

当您 运行 该代码时,您将收到错误:TypeError: Can't instantiate abstract class ListLike with abstract methods __delitem__, __getitem__, __len__, __setitem__, insert。一旦你实现了这些方法,你就会有一个类型,它的行为很像列表,但又不是。

要使 ListLikes 更像列表,请使用此代码比较两者:

example_list = list()
example_list_like = ListLike()

list_attributes = [attribute for attribute in dir(example_list)]
list_like_attributes = [attribute for attribute in dir(example_list_like)]

for attribute in list_attributes:
    if attribute not in list_like_attributes:
        print(f"ListLikes don't have {attribute}")
print("-----------")
for attribute in list_like_attributes:
    if attribute not in list_attributes:
        print(f"lists don't have {attribute}")

并相应地更改您的实现。