Is it possible to add an operation to a list in Python?

I pretty often use Python instead of pseudocode. For this, I would like to have a stack. I know that using lists is the way ( source ), but I would like to use myList.push , not myList.append , to make it clear that I am using the stack.

I thought I could do something simple, like

 myList.push = myList.append 

to define an alias for the add operation, but I get

  stack.push = stack.append AttributeError: 'list' object has no attribute 'push' 

Is there a short solution for adding a push operation to a list?

(This should not ruin my Python executable pseudo-code)

+6
source share
4 answers

You can subclass the list as follows:

 class List(list): def push(self, x): self.append(x) 

Use your own class like a regular list:

 >>> s = List() >>> s.push(10) >>> s.push(20) >>> s [10, 20] 
+12
source

Instead of overriding, how about smoothing the same function?

 class List(list): def __init__(self): self.push = self.append 

This will also preserve append functionality.

+5
source
 >>> a = [] >>> push = a.append >>> push(1) >>> a [1] >>> 
+1
source
 >>> stack = type('stack', (list,), {'push':list.append})() >>> stack.push(1) >>> stack.pop() 1 >>> 
0
source

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


All Articles