0

I'm creating a Node class that takes some parameters. One is called next which I would like to be set as None by the constructor if no value is supplied.

class Node(object):
    def __init__(self, next,data):
        self.data = data
        self.next = next

def X(self):
    node = Node(next ,data)

How can I do that?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • You can use a default value for it in function header `__init__(self,data,next=None)` – Mazdak Aug 13 '15 at 10:19
  • Read up on default values [here](https://docs.python.org/2/tutorial/controlflow.html#default-argument-values). – SuperBiasedMan Aug 13 '15 at 10:21
  • As an aside, what is the `Node.X` method for? It's not doing anything useful here. And by the way, it's not indented properly. – Cyphase Aug 13 '15 at 10:23

2 Answers2

2

Swap the order of the parameters to __init__() and give next a default value.

class Node(object):
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

    def X(self):
        node = Node(data)


node_a = Node('A')
node_b = Node('B', node_b)
Cyphase
  • 11,502
  • 2
  • 31
  • 32
1

Swap your arguments, and give next a default:

class Node(object):
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

then simply not pass in a next node when creating one:

def foo():
    node = Node(data)

or pass in another node as the second argument:

def bar():
    node = Node(data, some_other_node)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343