1.5 - Parent reference and backwards paths
We said that each item is enveloped into a bag node, and that can be contained by several bags in different places, this means that a Bag knows its children but ignores who is its father, in fact it may have many fathers.
We could set stricter hypotesis about the structure of a bag, making it more similar to a tree-leaf model, this would happen if a bag had a back reference to the bag that contains it. This feature is implemented by the method setBackRef() If we call the method setBackRef on a bag instance, that bag becomes the root of a tree structure in which each leaf (BagNode) knows its father. This means that we can traverse a bag backward using the property parent of bag's nodes.
family = Bag() family['grandpa'] = Bag() family['grandpa'].setBackRef() family['grandpa.father.son.nephew']=Bag() nephew = family['grandpa.father.son.nephew'] son = family['grandpa.father.son'] father = family['grandpa.father'] >>> son.parent == father True >>> nephew.parent.parent == father True >>> nephew.parent == son True
A bag with back reference can be traversed with special back-paths that use a new syntax. The symbol '../' in a path is equivalent to the property parent.
>>> nephew['../../'] == father True
When the backreference is set, it is possible to get from the bag its own BagNode:
>>> father.node BagNode : father at 432464
Attachments
- backref.jpg (23.9 kB) - added by anonymous 2 years ago.
- parentBag.py (0.9 kB) - added by anonymous 2 years ago.
- backref.2.jpg (24.8 kB) - added by anonymous 2 years ago.

