Home > OS >  Which dunder method (__method__) can replicate del obj[index] in custom data objects?
Which dunder method (__method__) can replicate del obj[index] in custom data objects?

Time:04-16

I am just experimenting with a hybrid model of Linked List with some modifications. I have already implemented object.delete_node(index) which just link the next node as it is in vanilla Linked Lists. Now, and want to implement del object[index] which does the same function as object.delete_node(index). How could I implement it? It is implemented in list and dict in Python. Which method is responsible for the same?

Below is the code for my LinkedList which works pretty well.

class Node:
    def __init__(self, data = None, next_pointer = None):
        self.data = data
        self.next_pointer = next_pointer

    def __str__(self):
        return self.__repr__()
    
    def __repr__(self):
        return str(self.data)


class LinkedList:
    def __init__(self):
        self.head = Node()
        self.length = 0

    def insert_node(self, data):
        new_node = Node(data) # node to be inserted
        current_node = self.head
        while current_node.next_pointer != None: # it'll only stop at the last node which is obviously empty
            current_node = current_node.next_pointer # bring out next pointer
        current_node.next_pointer = new_node

        self.length  = 1


    def delete_node(self, index):
        if self.length == 0: raise ValueError(f"Can not delete from empty Linked List")
        if (index > self.length - 1) or (index < -self.length -1): raise ValueError(f"index {index} out of bounds of max length")
        if index < 0: index = self.length   index

        count = 0
        current_node = self.head
        while count < index:
            current_node = current_node.next_pointer
            count  = 1

        current_node.next_pointer = current_node.next_pointer.next_pointer if current_node.next_pointer.next_pointer != None else None
        self.length -= 1


    def _slice_return(self, slice_index):
        '''
        Implement slicing Operation just like in Python Lists and Strings
        '''
        index = slice_index.start
        stop = min(slice_index.stop, self.length -1)
        step = 1 if slice_index.step == None else slice_index.step

        if index < 0: raise NotImplementedError("Negative slicing not implemented")

        if (index > self.length - 1) or (index < -self.length -1): raise ValueError(f"index {index} out of bounds of max length")
        if index < 0: index = self.length   index

        ll = LinkedList()
        for i in range(index, stop,step):
            ll.insert_node(self[i].data)
        return ll


    def __getitem__(self, index):
        if isinstance(index, slice):
            return self._slice_return(index)
            
        if (index > self.length - 1) or (index < -self.length -1): raise ValueError(f"index {index} out of bounds of max length")
        if index < 0: index = self.length   index
        
        count = 0
        current_node = self.head.next_pointer
        while count != index:
            current_node = current_node.next_pointer
            count  = 1
        
        return current_node


    def __len__(self):
        return self.length
    

    def __str__(self):
        array = []
        node = self.head
        count = self.length
        while count > 0:
            node = node.next_pointer
            array.append(node.data)
            count -= 1
            
        return(str(array))

    def __repr__(self):
        return self.__str__()


ll = LinkedList()
ll.insert_node("a")
ll.insert_node("b")
ll.insert_node("A")
ll.insert_node("B")

ll.delete_node(2) # delete 3rd node

CodePudding user response:

Answer based on @jonrsharpe comment:

There is a Datamodel section in python docs with list of available dunder methods

In your case its:

object.__delitem__(self, key)

Called to implement deletion of self[key]. Same note as for __getitem__(). This should only be implemented for mappings if the objects support removal of keys, or for sequences if elements can be removed from the sequence. The same exceptions should be raised for improper key values as for the __getitem__() method.

  • Related