Python Classes
Martin Franklin
martin.franklin at westerngeco.com
Thu Mar 7 05:45:28 EST 2002
Sam Collett wrote:
> I am quite new to Python and have no experience with classes. I have
> tried a file class, but I am not sure how to get it to work:
>
> class clFile(file):
>
> def getFileName(blnExt=None):
> """
> file = path to file
> blnExt = show file extension (put in value other than 0 or
> None to show the extension)
> """
> import os
> if blnExt:
> result = os.path.basename(file)
> else:
> result = os.path.splitext(os.path.basename(file))[0]
> del os
> return result
>
> def getFileExt():
> import os.path
> result = os.path.splitext(file)[1]
> del os
> return result
>
> def getDir():
> import os
> result = os.path.dirname(file)
> del os
> return result
>
> I wondered if there was a way to do something like the following:
>
> myfile = clFile("c:\\somedir\\dir with spaces\\foo.txt")
> myfile.getDir would return c:\somedir\dir with spaces\
> myfile.getFileExt would return .txt
> myfile.getFileName would return foo.txt or foo
Ok try this to get you working:
import os # do this at the top....
class clFile:
def __init__(self, file):
# constructor called when you create an instance (object) of this
class
self.file=file
# self.file instance variable bound to file object
#(in this case the file name passed to the class constructor)
def getFileName(self, blnExt=None):
# return filename with or without the extension..
if blnExt:
result = os.path.basename(self.file)
else:
result = os.path.splitext(os.path.basename(self.file))[0]
return result
def getFileExt(self):
# return file extension
return os.path.splitext(self.file)[1]
def getDir(self):
# return the file basname (directory/folder)
return os.path.dirname(self.file)
# now for testing.....
if __name__=='__main__':
clf=clFile('/home/bpse/crapola.bot') # create an instance of clFile
# call it's methods....
print clf.getFileExt()
print clf.getFileName(blnExt=1)
print clf.getFileName()
print clf.getDir()
You should really work your way through the tutorial (at least the classes
bit) on:-
http://www.python.org/doc/current/tut/tut.html
More information about the Python-list
mailing list