Search code examples
pythonclassoopobjectself

Basic object oriented implementation in python


Hello I am learning python and I have this working code but in most of Object Oriented examples of python, I see people use extra stuff and I am not sure why do we need those.

I will try to explain my question with comments in the code.

class Node:

    data = none
    next = none

# Question1: Why do we have these variables outside of 
# __init__ fucntion? what are their applications? 

    def __init__(self, val):
        self.data = val
        self.next = None
    def display(self):
        next = self
        while next.next:
            print next.data, "->",
            next = next.next
        print next.data

# Question2: Do we need getter setter functions to access 
# the attributes above? I was able to remove a node with 
# simple function and it worked well

def denode(node):
    node.next = node.next.next


# Question 3: for many implementation samples of a linked
# list or something that uses Node, I see that example
# uses another class, but in the example below I was able
# to create a linked list without any trouble. why do we 
# need a separate class to create a linked list?


#ex
node1 = Node(123)
node2 = Node(134)
node3 = Node(139)
node4 = Node(148)
node1.next=node2
node2.next= node3
node1.display()
denode(node1)
node1.display()

Solution

    1. The variables outside the __init__ method are called class variables and inside the method are called instance variables. This will answer your question: What is the difference between class and instance variables?
    2. In python, all variables are public so you don't need getter setter methods unless you want them in order to protect the variable value or you want to process / validate the value before setting / getting the variable. More is here: What's the pythonic way to use getters and setters?
    3. There is a design flaw in your code. The class Node represents one node. So, if I had to use this implementation I would expect all methods of Node would be in one node scope including display. You implemented Node.display() to display the whole linked list and therefor you "don't need" a LinkedList class. I think it is better to add a LinkedList class with a head variable to hold the first node and a display method just like you wrote to make it more intuitive.