Is it possible to override the assignment operator ('=') in Python?

Is there any for this? Maybe something like: (updated)

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 ... 

What I'm trying to do is implement a generalized tree structure that is as intuitive as possible (for me), and also integrates seamlessly with the Model-View-Delegate PyQt5 architecture.

I want to be able to set the incoming item_or_tree element to an element or tree. Therefore, I am looking to overload a function called when using the = operator on an element.

PyQt has this element-based architecture in which QAbstractItemModel is redefined. This (I assume) should return / accept QModelIndex objects. These are table trees (2D arrays).

So, I create a single tree structure that can contain itself, deal with two opposite indexing paradigms, and play fine with Python and everything else.

+5
source share
1 answer

Cannot override implementation x = y . See Facts and Myths about Python Names and Marks for details on what assignment means.

You can override xa = y , with __setattr__ , this is (roughly) x.__setattr__('a', y) .

You can override x[k] = y with __setitem__ , this is (approximately) x.__setitem__(k, y) .

But you cannot override x = y .

+15
source

Source: https://habr.com/ru/post/1200958/


All Articles