This is my first program in Python: a stack implementation.
class Stack: items =[]; index =-1; def isEmpty(self): return self.index >=0; def push(self,item): self.index +=1; print(self.index); self.items.insert(self.index,item); def pop(self): if self.index<0: raise Exception(" no items in list"); else: del self.items[self.index]; self.index -=1; def peek(self): print(self.index); if self.index >-1: return self.items[self.index];stackobj = Stack();stackobj.push("solomon");stackobj.push("helloworld")stackobj.pop();print(stackobj.peek())Even though this program works I'm still confused as to whether I've written the program in the right way. I am also not sure when to use theself operator.
1 Answer1
Welcome to the land of Python!
If you come from Java, think asself being the same asthis in Java.It is a reference to the object, the difference being in Python, you have to explicitly pass self as a parameter to the class methods.
If you write in Java
class Stack{ //constructor and class variables goes here void pop(){ if(this.index < 0) //logic of the function goes here }}In Python you write like you did here
class Stack: # constructor and class variables goes here def pop(self): if self.index<0: # logic of the function goes hereYou see thatself andthis serve the same purpose.
An another point, you should use documentation! As inPEP257 the format recommanded is like:
def complex(real=0.0, imag=0.0): """Form a complex number. Keyword arguments: real -- the real part (default 0.0) imag -- the imaginary part (default 0.0) """ if imag == 0.0 and real == 0.0: return complex_zero ... '''Another thing, to followPEP8 it is better to write assignment and condition with a space after the operator.Writeitems = [] orself.index >= 0 instead ofitems =[] orself.index >=0.
Also you can drop; in Python, it's not Java :)
Edit: Also look at @Jon's comments below
- 1\$\begingroup\$Some other things,
itemsshould be an instance attribute and not a class one,indexis redundant as you can dolen(items)and then you're not manually carrying it about somewhere else, and thepopmight as well useitems.pop(0)and optionally catch the exception and raise a more meaningful one - raisingExceptionis fairly broad...peekalso doesn't seem to mirror its behaviour and returnsNone. Also -if itemsis sufficient for an empty check - no need to check its length there.\$\endgroup\$Jon Clements– Jon Clements2018-01-06 14:06:17 +00:00CommentedJan 6, 2018 at 14:06 - \$\begingroup\$Some very good points!\$\endgroup\$Julien Rousé– Julien Rousé2018-01-06 14:17:11 +00:00CommentedJan 6, 2018 at 14:17
- \$\begingroup\$(and
.appendinstead of.insert) :)\$\endgroup\$Jon Clements– Jon Clements2018-01-06 14:20:01 +00:00CommentedJan 6, 2018 at 14:20
You mustlog in to answer this question.
Explore related questions
See similar questions with these tags.

