recursion in Class-methods?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Jun 26 05:06:07 EDT 2008


klant a écrit :
> do i need to call Graph.find_path?
 >
> 
>>>> g = Graph({'A': ['B', 'C'],
>              'B': ['C', 'D'],
>              'C': ['D'],
>              'D': ['C'],
>              'E': ['F'],
>              'F': ['C']})
>>>> g
> <__main__.Graph instance at 0x01D74378>
>>>> g.find_all_paths('A', 'C')
> 
> Traceback (most recent call last):
>   File "<pyshell#10>", line 1, in <module>
>     g.find_all_paths('A', 'C')
>   File "C:/Python25/Progs/pygameProgs/visualgraph/graph.py", line 26,
> in find_all_paths
>     newpaths = find_all_paths(self.dictionary, node, end, path)
> NameError: global name 'find_all_paths' is not defined
>>>> g.find_path('A', 'C')
> 
> Traceback (most recent call last):
>   File "<pyshell#11>", line 1, in <module>
>     g.find_path('A', 'C')
>   File "C:/Python25/Progs/pygameProgs/visualgraph/graph.py", line 13,
> in find_path
>     newpath = find_path(self.dictionary, node, end, path)
> NameError: global name 'find_path' is not defined
 >
> 
> 
> 
> class Graph:

Unless you need to ensure compat with ages-old Python versions, better 
to use newstyle classes:

class Graph(object):

>     def __init__(self, dictionary):
>         self.dictionary = dictionary
> 
>     def find_path(self, start, end, path=[]):

http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

Unless you exactly what you're doing (and given your current problem, I 
can tell it's not the case), *don't* use mutable containers as default 
function argument values.


      def find_path(self, start, end, path=None):
          if path is None:
              path = []

>         path = path + [start]

           path.append(start)

>         if start == end:
>             return path
>         if not self.dictionary.has_key(start):

           if start not in self.dictionnary:

>             return None


>         for node in self.dictionary[start]:
>             if node not in path:
>                 newpath = find_path(self.dictionary, node, end, path)

                   newpath = self.find_path(...)





(snip remaining code - same problems, same solutions...)



More information about the Python-list mailing list