0

I'm trying to define a class which takes in a default parameter for its init function. I've defined a class as follows:

class Node:
    def __init__(self,name,visited=False,distance=math.inf,path=Node('-')):
        self.name = name
        self.visited = visited
        self.distance = distance
        self.path = path

and I get the following error:

NameError: name 'Node' is not defined

I was able to get around this problem by "pre-defining" the parts of the class that I needed, like so:

class Node:
    def __init__(self,name):
        self.name = name

class Node:
    def __init__(self,name,visited=False,distance=math.inf,path=Node('-')):
        self.name = name
        self.visited = visited
        self.distance = distance
        self.path = path

but I can't shake the feeling there's a better, more pythonic way.

8
  • 1
    Why is class taking itself as a parameter? Commented May 2, 2020 at 2:23
  • 1
    What should the path be for the Node object you'd be setting as the default? Commented May 2, 2020 at 2:26
  • 1
    Sure, but does the dummy node point to itself, or to some other Node object? What does the first Node to ever exist point to, when there don't exist any other Nodes yet? Commented May 2, 2020 at 2:56
  • 1
    I see what you're getting at after reading through juanpa's answer. I've accepted his 'default-path' solution. Commented May 2, 2020 at 3:03
  • 1
    Another alternative is just to use a sentinel object as the default value for that Node, even just SENTINEL = object() Commented May 2, 2020 at 3:21

1 Answer 1

2

You should do this:

class Node:
    def __init__(self, name, visited=False, distance=math.inf, path=None):
        self.name = name
        self.visited = visited
        self.distance = distance
        if path is None:
            self.path = Node('-', path="default-path")
        else:
            self.path = path

This is the idiom you should be following with mutable default arguments to begin with.

However, you need the default to have a path, or it will recurse without stopping.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm pretty sure this recurses forever, since the new node you create needs a path value of its own.
@Blckknght yes, yes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.