recursive file editing

Peter Otten __peter__ at web.de
Tue Apr 6 09:08:37 EDT 2004


TaeKyon wrote:

> Il Sun, 04 Apr 2004 12:11:25 +0200, Peter Otten ha scritto:
> 
>> The following code comes with no warranties. Be sure to backup valuable
>> data before trying it. You may need to edit the regular expressions. Call
>> the script with the directory you want to process.
> 
> Seems to work all right !
> I have a question:
> 
>> class Path(object):
> # multiple function definitions follow, amongst which:
> 
>> def files(rootfolder):
>>     for folder, folders, files in os.walk(rootfolder):
>>         for name in files:
>>             yield Path(folder, name)
> 
> So 'Path' is the name of a class and _contemporaneously_ the
> result of one of the functions the class contains ?

No, the functions up to __str__() are indented one level. This means they
belong to the Path class, i. e. they are methods.
In contrast, files() is a standalone function - or more precisely a
generator. As a rule of thumb you can tell functions from methods by
looking at the first parameter - if it's called "self" it's a method.

As a side note, though it's not the case here it is possible for a class to
have methods that return new instances of the same class (or even the same
instance which is what a considerable fraction of python users wishes for
list.sort()).
For example:

class Path(object):
    # ... as above
    def child(self, name):
        """ create a new Path instance denoting a 
            child of the current path """
        return Path(self.path, name)
    def __repr__(self):
        """ added for better commandline experience :-) """
        return "Path(%r)" % self.path   

Now try it:

>>> from processtree import Path
>>> p = Path("/path/to", "folder")
>>> p.child("file")
Path('/path/to/folder/file')
>>> p.child("sub").child("subsub")
Path('/path/to/folder/sub/subsub')

> Or are there really two separate 'Path' things which don't interfere
> because each has its own namepace ?

No, every Path(folder, name) creates a new Path instance as defined above.
When you see Class(arg1, arg2, ..., argN), under the hood Python creates a
new instance of Class and calls the special __init__(self, arg1, ..., argN)
method with the instance as the first (called self by convention) and
arg1,..., argN as the following arguments.

> I'm sorry for the repeated questions, maybe I should take this discussion
> over to the tutor mailing list !

I suggest that you stick with with the simpler approach in my later post
until you have a firm grip of classes. For the task at hand the Path class
seems overkill, now I'm reconsidering it.

Peter



More information about the Python-list mailing list