Calling instance variable directly vs calling a method that returns instance variable

Hi,
I am attempting the Linked List Implementation II exercise on the computer science path.

I have the following class:

class LinkedList:
  def __init__(self, value=None):
    self.head_node = Node(value)
  
  def get_head_node(self):
    return self.head_node

Later in the class, I want to have a method def stringify_list(self): that requires the use of self.head_node.

My question is; is there any difference between calling self.get_head_node() [1] and calling self.head_node [2] ??
[1]

  def stringify_list(self):
    string_list = ""
    current_node = self.get_head_node()

[2]

def stringify_list(self):
    string_list = ""
    current_node = self.head_node

Thank you,

At present, not really but this would be an example of using an accessor (more specifically it’s a getter). There are arguments for and against using them, the following is a link to a Java related question- java - Why use getters and setters/accessors? - Stack Overflow but the reasoning for most of it can be applied to Python (maybe read more than one answer).

You’ll rarely see that style of accessor though as Python would typically use a property which is generally a more convenient way of doing this that can be implemented at any point (assuming you actually needed an accessor as most Python guidance suggests avoiding them unless they’re required).

Might also be a worthwhile read:

For the lessons though I think you’ll just have to stick close to the instructions for the sake of passing any tests. Worth knowing the pros/cons and any potential alternatives though.

3 Likes