是否可以在Python中覆盖赋值('=')运算符?

时间:2014-08-22 22:30:16

标签: python python-3.x operator-overloading

这有没有dunder?也许是这样的:(更新)

class Tree:
    def __init__(self, item_or_tree):
        self._setto(item_or_tree)

    def __assign__(self, val):
        self._setto(item_or_tree)

    def __setitem__(self, which, to_what):
        ## I would like this to call __assign__ on the Tree object at _tree[which]
        to_what._tree[which] = to_what

    def __getitem__(self, which):
        return self._tree[which]

    def __len__(self): return len(self._tree)

    def __eq__(self, other):
        if isinstance(other, Tree):
            if other._is_tree:
                return (self._item == other._item) and (self._tree == other._tree)
            else:
                return self._item == other._item
        else: return self._item == other

    def _setto(self, item_or_tree):
        if isinstance(item_or_tree, Tree):
            self._set_from_Tree(item_or_tree)
        elif isinstance(item_or_tree, dict):
            self._set_from_dict(item_or_tree)
        else:
            self._set_from_other(item_or_type)


    def _set_from_Tree(self, other_Tree):
        self._tree = other_Tree[:]
        self._item = other_Tree
        self._is_tree = other_Tree._is_tree

    def _set_from_dict(self, the_dict):
        self._is_tree = True
        self._item = None
        self._tree = {}
        for key, val in the_dict.items():
            self._tree[key] = Tree(val)

    def _set_from_other(self, other):
        self._is_tree = False
        self._tree = None
        self._item = other

class TreeModel(Tree, QAbstractItemModel):
    ...
    ## a whole bunch of required overrides
    ## etc
    ...

我要做的是实现一个通用树结构,尽可能直观地(对我而言),并与PyQt5的Model-View-Delegate架构无缝集成。

我希望能够将传入的item_or_tree设置为项目或树。所以我希望重载在项目上使用=运算符时调用的函数。

PyQt具有基于项目的体系结构,其中覆盖了QAbstractItemModel。这是(我猜)应该返回/接受QModelIndex对象。这些是表树(2D数组)。

因此,我正在创建一个可以包含自身的单个树结构,处理2个相反的索引范例,并且可以很好地处理Python和其他所有内容。

1 个答案:

答案 0 :(得分:18)

无法覆盖x = y的实施。有关分配的含义的详细信息,请参阅Facts and Myths about Python Names and Values

您可以使用x.a = y覆盖__setattr__,(大致)x.__setattr__('a', y)

您可以使用x[k] = y覆盖__setitem__,它是(大致)x.__setitem__(k, y)

但是你无法覆盖x = y