Data Structures: Properties vs Methods

Hi there!

I am currently doing the Data Structures and Algorithms for Python course on Codecademy, and have gone through linked lists, doubly linked lists, queues, and stacks so far.

Why is it that we create methods to access properties rather than accessing them directly? Not sure if there is a practical reason for it that I haven’t realized yet.

For example, creating a get_size() method as below, vs accessing size using just by self.size?

class Stack: def __init__(self, value, limit=5000): self.size = 0 self.limit = limit self.top_value = None def get_size(self): return self.size

Hi,
It’s to do with Encapsulation (one of the 4 pillars of Object-Oriented-Programming).
What it’s aim is, is to keep different parts of program separate from each other. Hopefully, this should make it harder to accidentally alter something you didn’t intend to, or should you alter stuff inside the class, you shouldn’t need to alter all the code that references it.
Unfortunately, it’s a little woolly in Python as you can still access properties directly, but it’s a good habit to get used to, especially if you plan to use more Object-Oriented languages, such as C#, Java, etc, which have modifiers which can limit access for various parts of the program.

Hope that helps

Thanks for clearing that up for me, this helps a lot! Haven’t had a go at any truly OOP languages yet, but I plan to in the future so this is good to keep in mind.

Thanks for the help! Now I’m off to go read up more on those 4 pillars now :eyes: