How to set a class attribute a specified number of times in Python
<p>Suppose we have a class <code>Node</code> which is initialized as follows:</p>

<pre><code>class Node(object):
    def __init__(self, data=None, next_node=None, prev_node = None):
        self.data = data
        self.next = next_node
        self.prev = prev_node
</code></pre>

<p>and we create an instance <code>head</code> as follows:</p>

<pre><code>head = Node(data=4)
head.next = Node(data=5)
head.next.next = Node(data=6)
head.prev = Node(data=2)
</code></pre>

<p>I'd like to add another node to the doubly-linked list, which I could do by</p>

<pre><code>head.next.next.next = Node(data=8)
</code></pre>

<p>However, instead of writing ".next" three times, I would like to use a method which takes as input the number of times to call ".next" - that is, something like <code>head.next_n_times(3) = Node(data=8)</code> which would have the same effect. How could I achieve this?</p>

<p>Here is what I've tried so far:</p>

<pre><code>class Node(object):
    def __init__(self, data=None, next_node=None, prev_node = None):
        self.data = data
        self.next = next_node
        self.prev = prev_node

    def next_n_times(self, n):
        next_node = self.next
        for i in range(n-1):
            next_node = next_node.next
        return next_node

head = Node(data=4)
head.next = Node(data=5)
head.next.next = Node(data=6)
head.prev = Node(data=2)
data = 5

head.next_n_times(3) = Node(data=8)
</code></pre>

<p>However, I get the error message</p>

<pre><code>File "sorted_insert_scratch.py", line 19
    head.next_n_times(5) = Node(data=8)
SyntaxError: can't assign to function call
</code></pre>

<p>It seems like the <code>next_n_times</code> method works as a 'getter', but not as a 'setter'. How can I make it work as a 'setter'?</p>

<p>You're trying to implement the append method for the Node class. You can easily do so with recursion:</p>

<pre><code>class Node(object):
    def __init__(self, data=None, next_node=None, prev_node = None):
        self.data = data
        self.next = next_node
        self.prev = prev_node

    def append(self, node):
        if self.next:
            self.next.append(node)
        else:
            self.next = node
            self.next.prev = self
</code></pre>

python