Managing Attribute Deletion
Managing Attribute Deletion. It’s possible to create properties that implement deletion functionality. This might be a rare use case of
property(), but having a way to delete an attribute can be handy in some situations.
00:17 Let’s say you are implementing your own tree data type. A tree is an abstract data type that stores elements in a hierarchy. The tree components are commonly known as nodes.
00:29 Each node in a tree has a parent node, except for the root node. Nodes can have zero or more children. Now suppose you need to provide a way to delete or clear the list of children of a given node.
Here’s an example that implements a tree node that uses
property() to provide most of its functionality, including the ability to clear the list of children of the node at hand.
TreeNode represents a node in your custom tree data type. Each node stores its children in a Python list. You then implement
.children as a property to manage the underlying list of children.
The deleter method calls
.clear() on the list of children to remove them all.
Here, you first create a
root node to start populating the tree. Then you create two new nodes and assign them to
.children using a list.
del statement triggers the internal deleter method of
.children and clears the list. In the next section of the course, you’ll see how to make class APIs that are backwards-compatible.
Become a Member to join the conversation.