walk calling visit within a class?

Gordon McMillan gmcm at hypernet.com
Fri Oct 29 12:28:47 EDT 1999


Betancourt, Josef asks:

>    This is probably a dumb question but.... Lets say I have a
>    class:
> 
> class theclass
>       def aVisit(self, pat, dirname, dirlist):
>   ............
> 
>  def testfiles(self, patobject, targetpath):
>   os.path.walk( targetpath, self.aVisit, self.patobject)
> 
> #end class theclass
> 
> Since os.path.walk requires a visit function that has an argument
> signature of:  (arg, dirname, names), how is a visit member
> function used within a class?  Or can someone fill in the whole I
> have in my Python fundamentals?

You're on the right track.

Fundamentals: theclass.aVisit is an "unbound" method; 
calling it will require an instance of theclass as the first arg.

x = theclass()
x.aVisit is a "bound" method - the self arg has been squirreled 
away in the binding. It can therefor be called just like it was a 
function. 

This code works:

import os

class theclass:
    def __init__(self):
        self.patobject = []
        
    def aVisit(self, pat, dirname, dirlist):
          print "aVisit called on", dirname

    def testfiles(self, targetpath):
         os.path.walk( targetpath, self.aVisit, self.patobject)

x = theclass()
x.testfiles('c:/temp')

- Gordon




More information about the Python-list mailing list