Home > Software design >  Difference between calling a function using dot notation vs. using it as an argument in the function
Difference between calling a function using dot notation vs. using it as an argument in the function

Time:10-08

I have some code that performs a basic Depth-First Search:

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

    def addChild(self, name):
        self.children.append(Node(name))   #recall I came across this before- 'Node(name)' is a node
        return self

    def depthFirstSearch(self, array): #self in this case is the root
        array.append(self.name)
        for child in self.children: 
            child.depthFirstSearch(array)
        return array

My question is around the second last line child.depthFirstSearch(array), instead of this, can we do depthFirstSearch(child,array)? Would these be equivalent, because the latter is how I normally would call the function, instead of using dot notation.

I can see one reason why it would not really make sense, because for the third last line we would have child.children, which doesn't exist?

Lastly, when do we use dot notation in general? Or is it not necessary if we don't want to use it.

CodePudding user response:

The simple answer is, yes, you can remove the dot notation around depthFirstSearch(), but it would be considered slightly worse than what you have now:

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

    def addChild(self, name):
        self.children.append(Node(name))   #recall I came across this before- 'Node(name)' is a node
        return self

    def depthFirstSearch(self, array): #self in this case is the root
        array.append(self.name)
        for child in self.children: 
            child.depthFirstSearch(array)
        return array

# Free function version of depthFirstSearch()
def depthFirstSearch(node, array):
    array.append(node.name)
    for child in node.children: 
        depthFirstSearch(child, array)
    return array

root = Node('root')   # My guess at how you generate a root

...   # Add more children to root and more children to those Nodes

array = root.depthFirstSearch([])  #My guess at how you call this now

array = depthFirstSearch(root, [])   #You can call the free function like this

The reason why your original code is preferred is that the free function accesses attributes that it shouldn't need to know about. There is the name of the Node: node.name and the children of the Node: node.children

  • Related