在Python3.4中,我想调用一个在父函数之外定义的子函数,它仍然可以访问父函数的作用域(参见下面的示例)。虽然为了便于查看,我在下面的示例中将函数命名为parent和child,但我所考虑的函数具有非常独立的任务,因此单独定义它们更有意义。我习惯于在JavaScript中执行以下操作:def parent():
test = 0
child()
def child():
test += 1
print(test)
但是,我只是在执行上面的代码时得到一个错误。我尝试了第二个变体,使用“nonlocal”关键字也失败了:
^{pr2}$
错误消息为“找不到非本地”test“的绑定”。在python中是否可以像其他许多语言一样实现这一点,或者是以下选项的唯一选项(不是首选):def parent():
test = 0
def child():
nonlocal test
test += 1
print(test)
child()
编辑:将父变量传递给子函数在我的用例中不起作用,因为我需要修改父变量。在
编辑2:父方法和子方法已经是一个类的一部分,它在逻辑上没有计数器的属性。计数器是两个函数内部的东西,用于在图形中跟踪节点访问(请参阅下面的实际示例):class Graph():
def depthFirstSearch(self):
for vertex in self.adjacency_list:
vertex.status = "not visited"
vertex.previous = None
visit_count = 0
for vertex in self.adjacency_list:
if vertex.status == "not visited":
self.depthFirstSearchVisit(vertex)
def depthFirstSearchVisit(self, vertex):
nonlocal visit_count
visit_count += 1
vertex.distance = visit_count
vertex.status = "waiting"
for edge in vertex.edges:
if edge.status == "not visited":
edge.previous = vertex
self.depthFirstSearchVisit(edge)
vertex.status = "visited"
visit_count += 1
vertex.distance_finished = visit_count