Classes in Python

I am interested why do we need special methods in class that just return instance variables if we can directly refer to these variables.

class Stack:
  def __init__(self, name):
    self.size = 0
    self.top_item = None
    self.limit = 1000
    self.name = name

  def get_size(self):
    return self.size
  
  def get_name(self):
    return self.name


stack = Stack('smth')

# difference??
stack.name
stack.get_name()

Thank you!

Was this in a CC lesson? If so, it may be an example for illustrative purposes only. What might be a benefit of using a method when other functions use an instance of Stack?

I think this is a potentially tricky question that has a few deep rabbit holes, like the nature of getters and setter in python vs. languages like java.

Check other sources if you’re curious like (https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters).

1 Like