J'ai écrit un petit extrait qui calcule la longueur du chemin d'un noeud donné (par exemple, la distance au nœud racine):Python: Comportement étrange de la fonction récursive avec des arguments de mot-clé
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)
Maintenant, il y a un chose étrange qui se passe avec cette fonction (au moins c'est étrange pour moi): Appeler node_depth pour la première fois renvoie la bonne valeur. Toutefois, l'appeler une seconde fois avec le même nœud renvoie -1. Les colored_nodes ensemble est vide dans le premier appel, mais contient tous les noeuds-ID dans le second appel qui ont été ajoutés au cours de première:
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
Suis-je manque quelque chose spécifique à Python ici et cela est vraiment censé Être comme ça?
Merci à l'avance,
Jena
La même chose mordre moi et j'ai trouvé votre question et une autre explication de SO de détail. http://stackoverflow.com/questions/1132941/least-astonishment-in-python-which-scope-is-the-mutable-default-argument-in – Yefei