Accessing parent function's variable in a child function called in the parent using python

前端 未结 2 1266
心在旅途
心在旅途 2021-01-22 17:46

In Python 3.4, I would like to call a child function, defined outside the parent function, that still has access to the parent function\'s scope (see example below). While I ha

相关标签:
2条回答
  • 2021-01-22 17:58

    In this case, you'd probably like to use a class. They are really easy to get your head around. Note the self variable that is passed, and take a look here for a quick explanation of scope in classes.

    #!/usr/bin/env python3
    
    class Family(object):
    
        def parent(self):
            self.test = 0
            self.child()
    
        def child(self):
            self.test += 1
            print(self.test)
    
    if __name__ == "__main__":
        Family().parent()
    

    So, to translate to your code:

    #!/usr/bin/env python3
    
    class Graph(object):
        def depthFirstSearch(self):
            for vertex in self.adjacency_list:
                vertex.status = "not visited"
                vertex.previous = None
    
            self.visit_count = 0
            for vertex in self.adjacency_list:
                if vertex.status == "not visited":
                    self.depthFirstSearchVisit(vertex)
    
        def depthFirstSearchVisit(self, vertex):
            self.visit_count += 1
    
            vertex.distance = self.visit_count
            vertex.status = "waiting"
    
            for edge in vertex.edges:
                if edge.status == "not visited":
                    edge.previous = vertex
                    self.depthFirstSearchVisit(edge)
    
            vertex.status = "visited"
            self.visit_count += 1
            vertex.distance_finished = self.visit_count
    
    class Edge(object):
        status = "not vistited"
    
    class Vertex(object):
        def __init__(self):
            self.edges = [Edge(), Edge()]
    
    if __name__ == "__main__":
        graph = Graph()
        graph.adjacency_list = [Vertex(), Vertex()]
        graph.depthFirstSearch()
    

    Nothing fancy needed.

    0 讨论(0)
  • 2021-01-22 18:15

    You can define a function attribute like parent.test = 0 outside the function and access it in the child function using parent.test

    0 讨论(0)
提交回复
热议问题