kelime argümanlarla özyinelemeli fonksiyon Garip davranışları (örneğin kök düğüme olan uzaklığı):Python: Ben belli bir düğümün yol uzunluğunu hesaplar küçük bir parçasını yazdım
def node_depth(node, depth=0, colored_nodes=set()):
"""
Return the length of the path in the parse tree from C{node}'s position
up to the root node. Effectively tests if C{node} is inside a circle
and, if so, returns -1.
"""
if node.mother is None:
return depth
mother = node.mother
if mother.id in colored_nodes:
return -1
colored_nodes.add(node.id)
return node_depth(mother, depth + 1, colored_nodes)
Şimdi orada bir Bu işlevin gerçekleşmesiyle ilgili garip bir şey (en azından benim için garip): İlk defa node_depth çağrısı doğru değeri döndürüyor. Ancak, aynı düğümde ikinci kez çağırmak -1 değerini döndürür. set colored_nodes ilk çağrıda boştur, fakat ilki sırasında eklenen ikinci aramada tüm düğüm-Kimliği içeriyor:
print node_depth(node) # --> 9
# initially colored nodes --> set([])
print node_depth(node) # --> -1
# initially colored nodes --> set([1, 2, 3, 38, 39, 21, 22, 23, 24])
print node_depth(node, colored_nodes=set()) # --> 9
print node_depth(node, colored_nodes=set()) # --> 9
Burada bazı Python özgü bir şey eksik muyum ve bu gerçekten gerekiyordu Bu şekilde ol? peşin
sayesinde
Jena
Aynı şey beni ısırdı ve ben senin sorununun ve başka bir detay açıklamasının olduğunu buldum. http://stackoverflow.com/questions/1132941/least-astonishment-in-python-which-scope-is-the-mutable-default-argument-in – Yefei