Hi,everyone. I've been trying to extend Python's file type but I'm new to Python so I don't know if I'm going about it the right way. I hope someone can help me out with this or point me in the right direction.
The problem isn't really subclassing file, but a function I tried adding to it.
What I want to do is have an instance of my class, let's call the class Subfile, and obtain a list of Subfiles from it in case it is a directory, so I can then iterate over them and use the functions I defined for the class.
I think it's easier to see it with an example:

class Subfile(file):
 
     def __init__(self, path):
         if(not os.path.isdir(path):
             file.__init__(self, path)
         self.__path = path
 
     def listFiles(self):
         if(os.path.isdir(self.__path)):
             for file in os.listdir(os.path.abspath(self.__path)):
                 yield Subfile(os.path.abspath(self.__path) + "/" + file)
 
     def someFunction(self):
         print "Did something"
 
 subfile = Subfile("some/dir")
 for file in subfile.listFiles():
     file.someFunction()

The idea is to create an instance of Subfile for some directory, to use some functions I defined and then get an instance of Subfile for the files under that directory so I can use some other functions on them.

However, when I try doing something like this, I get the following error message:

Traceback (most recent call last):
File "XXXX", line 94, in <module>
for file in dir.listFiles():
File "XXXX", line 52, in listFiles
yield PRFile(os.path.abspath(self.__path) + "/" + file)
File "XXXX", line 20, in __init__
file.__init__(self, path)
TypeError: __init__() takes exactly 2 arguments (3 given)

Could someone tell me what I'm doing wrong?

Thank you very much in advance and sorry for the lengthy question :)

Your problem may be that you are also using file for variable names.

Also
if(not os.path.isdir(path):
should be
if not os.path.isdir(path):

This works (Windows XP) ...

import os

class Subfile(file):
    def __init__(self, path):
        if not os.path.isdir(path):
            file.__init__(self, path)
        self.__path = path
 
    def listFiles(self):
        if os.path.isdir(self.__path):
            for file1 in os.listdir(os.path.abspath(self.__path)):
                yield Subfile(os.path.abspath(self.__path) + "/" + file1)
 
    def someFunction(self):
        print "Did something", self.__path
 

path = "C:/Temp"
subfile = Subfile(path)
for file1 in subfile.listFiles():
    file1.someFunction()

Ohh, of course. Haha, thanks, I was fighting with this for hours yesterday.
Thank you very much for your reply.
Greetings!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.