-2

I am newbie so thank you in advance

class stack():
    def __init__(self):
        self._stack = []
    
    def push1(self, item):
        self._stack.append(item)
import test1 
a = test1.stack()
a.push1(5)

In this code it works when write in the command prompt what is above and also the code in itself in test1 module

class StackEmptyException(Exception):
    pass

class my_stack:
  def __init__(self):
    self._stack = []

def check_input_type(inp):
  if not isinstance(inp, my_stack):
    raise TypeError('Expected stack; got %s' % type(inp).__name__)

def push(item, st:my_stack):
  check_input_type(st)
  st._stack.append(item)

def push1(self, item):
  self._stack.append(item)
  
def pop(st:my_stack):
  check_input_type(st)
  to_return = None
  try:
    to_return = st._stack[-1]
    st._stack = st._stack[:-1]
  except IndexError:
    raise StackEmptyException("Stack is empty") from None
  return to_return

def top(st:my_stack):
  check_input_type(st)
  to_return = None
  try:
    to_return = st._stack[-1]
  except IndexError:
    raise StackEmptyException("Stack is empty") from None
  return to_return

def is_empty(st:my_stack):
  check_input_type(st)
  return len(st._stack) == 0

def create_stack():
  return my_stack() 

However in this code when I try to to same thing it throws error

import my_stack
a = my_stack.my_stack()
a.push1(5)

AttributeError: 'my_stack' object has no attribute 'push1'

and something I didn't understand in the second part of the code why there is st:my_stack() in some functions parameters how is work what can I also may right to replace it
the code is in my_stack module

  • 1
    You need to indent your method definitions to make them part of the class. Your first version of the code has correct indentation, your second version does not. – Samwise Feb 28 '22 at 20:38
  • This is sufficiently basic Python syntax that I suggest taking a step back from the project you're working on right now, and going through a beginner Python tutorial *step by step* instead of diving into trying to understand someone else's code when you haven't learned the language yet. – Samwise Feb 28 '22 at 20:42

1 Answers1

0

As others mentioned, you need to indent push1 so Python knows it's an attribute of your my_stack class

class my_stack:
  def __init__(self):
    self._stack = []
  
  #Notice push1 is indented
  def push1(self, item):
    self._stack.append(item)
Stephan
  • 5,891
  • 1
  • 16
  • 24