【问题标题】:Is it possible to override the assignment ('=') operator in Python?是否可以覆盖 Python 中的赋值 ('=') 运算符?
【发布时间】:2014-10-16 20:44:53
【问题描述】:

这有什么特别之处吗?也许类似于:(更新)

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 的模型-视图-委托架构无缝集成。

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

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

所以我正在创建一个可以包含自身的单一树结构,处理两种相反的索引范例,并且可以很好地与 Python 和其他一切配合使用。

【问题讨论】:

  • 我认为这会违反 Python 的对象模型或变量/命名方案。名称不仅仅代表一个对象,而只是指向引擎盖下的一个对象。使用赋值运算符只是更改名称指向的对象。
  • 因为那样的话,一旦分配给一个变量,就不可能再用那个标签做任何事情了?
  • 没有什么比 Python 的工作方式更进一步了。赋值甚至不触摸对象,它操纵名称。您应该描述您要解决的问题,以便我们可以专注于如何实现这一目标。
  • @delnan 是的,这就是我所担心的。我要做的是实现一个通用的树对象,以便能够轻松地与我的其余代码和 PyQt5 的模型视图架构一起使用。我会在问题中详细说明,请稍等。
  • Property assignments/set'ing (对于给定的对象)可以被截获.. 不确定这是否有任何用途,或者在上下文中值得探索的路径。参考。 intermediate-and-advanced-software-carpentry.readthedocs.org/en/…

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


【解决方案1】:

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

你可以覆盖x.a = y,用__setattr__,它(大致)是x.__setattr__('a', y)

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

但你不能覆盖x = y

【讨论】:

  • 很伤心..但可以理解。谢谢
猜你喜欢
  • 2020-09-11
  • 2010-10-13
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-23
  • 2019-10-08
相关资源
最近更新 更多