Sign in to follow this  
revisioned

[python] classes help

Recommended Posts

Does anyone know any good articles on classes and OOP for python? I've read about classes in 3 different books (byte of python, thinkCS, and dive into python) thinkCS barely covers them along with byte but when I read about them in dive it went through alot about them and I was COMPLETELY lost for the most part I get really confused when it comes to working between ascendants and descendants and when to use self, how to call things between them etc thanks

Share this post


Link to post
Share on other sites
Is it that you get confused on the syntax that Python uses? You understand and can use OOP designs, you just have trouble with using Python and OOP together.

Or do you have trouble with OOP itself? You see the syntax, but it's like hitting a wall, or having everything go through your head? That is, you understand the syntax, but cannot fathom how you might possibly use it in any code you write?

Share this post


Link to post
Share on other sites
I think i'm having trouble understanding some of the the syntax and rules not OOP itself ( i don't even know if that makes sense O.o) when it gets into using classes within classes and some of the more advanced things


this is the code the chapter goes through explaining:

[source lang=python] 
"""Framework for getting filetype−specific metadata.
Instantiate appropriate class with filename. Returned object acts like a
dictionary, with key−value pairs for each piece of metadata.
import fileinfo
info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3")
print "\\n".join(["%s=%s" % (k, v) for k, v in info.items()])
Or use listDirectory function to get info on all files in a directory.
for info in fileinfo.listDirectory("/music/ap/", [".mp3"]):
...
Framework can be extended by adding classes for particular file types, e.g.
HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each class is completely responsible for
parsing its files appropriately; see MP3FileInfo for example.
"""
import os
import sys
from UserDict import UserDict
def stripnulls(data):
"strip whitespace and nulls"
return data.replace("\00", "").strip()
class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
class MP3FileInfo(FileInfo):
"store ID3v1.0 MP3 tags"
tagDataMap = {"title" : ( 3, 33, stripnulls),
"artist" : ( 33, 63, stripnulls),
"album" : ( 63, 93, stripnulls),
"year" : ( 93, 97, stripnulls),
"comment" : ( 97, 126, stripnulls),
"genre" : (127, 128, ord)}
def __parse(self, filename):
"parse ID3v1.0 tags from MP3 file"
self.clear()
try:
Dive Into Python 47
fsock = open(filename, "rb", 0)
try:
fsock.seek(−128, 2)
tagdata = fsock.read(128)
finally:
fsock.close()
if tagdata[:3] == "TAG":
for tag, (start, end, parseFunc) in self.tagDataMap.items():
self[tag] = parseFunc(tagdata[start:end])
except IOError:
pass
def __setitem__(self, key, item):
if key == "name" and item:
self.__parse(item)
FileInfo.__setitem__(self, key, item)
def listDirectory(directory, fileExtList):
"get list of file info objects for files of particular extensions"
fileList = [os.path.normcase(f)
for f in os.listdir(directory)]
fileList = [os.path.join(directory, f)
for f in fileList
if os.path.splitext(f)[1] in fileExtList]
def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]):
"get file info class from filename extension"
subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:]
return hasattr(module, subclass) and getattr(module, subclass) or FileInfo
return [getFileInfoClass(f)(f) for f in fileList]
if __name__ == "__main__":
for info in listDirectory("/music/_singles/", [".mp3"]):
print "\n".join(["%s=%s" % (k, v) for k, v in info.items()])
print
T





edit: the site doesn't keep the indents so I guess it's not easy to follow on here

[Edited by - revisioned on July 25, 2008 12:14:45 AM]

Share this post


Link to post
Share on other sites
Python RELIES on proper indentation, so that code you posted only MAY be readable. But, regardless, I won't bother because I never got deep enough into Python to solve your problem.

Put source lang="python" (in square brackets [] ) before your code, /source after, and repost.

Share this post


Link to post
Share on other sites
Quote:
Original post by revisioned
this is the code the chapter goes through explaining:

 
"""Framework for getting filetype−specific metadata.
Instantiate appropriate class with filename. Returned object acts like a
dictionary, with key−value pairs for each piece of metadata.

import fileinfo
info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3")
print "\\n".join(["%s=%s" % (k, v) for k, v in info.items()])
Or use listDirectory function to get info on all files in a directory.
for info in fileinfo.listDirectory("/music/ap/", [".mp3"]):
...

Framework can be extended by adding classes for particular file types, e.g.
HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each class is completely responsible for
parsing its files appropriately; see MP3FileInfo for example.
"""


import os
import sys
from UserDict import UserDict

def stripnulls(data):
"strip whitespace and nulls"
return data.replace("\00", "").strip()

class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename

class MP3FileInfo(FileInfo):
"store ID3v1.0 MP3 tags"
tagDataMap = {"title" : ( 3, 33, stripnulls),
"artist" : ( 33, 63, stripnulls),
"album" : ( 63, 93, stripnulls),
"year" : ( 93, 97, stripnulls),
"comment" : ( 97, 126, stripnulls),
"genre" : (127, 128, ord)}

def __parse(self, filename):
"parse ID3v1.0 tags from MP3 file"
self.clear()

try:
Dive Into Python 47
fsock = open(filename, "rb", 0)
try:
fsock.seek(−128, 2)
tagdata = fsock.read(128)
finally:
fsock.close()
if tagdata[:3] == "TAG":
for tag, (start, end, parseFunc) in self.tagDataMap.items():
self[tag] = parseFunc(tagdata[start:end])
except IOError:
pass

def __setitem__(self, key, item):
if key == "name" and item:
self.__parse(item)
FileInfo.__setitem__(self, key, item)

def listDirectory(directory, fileExtList):
"get list of file info objects for files of particular extensions"
fileList = [os.path.normcase(f)
for f in os.listdir(directory)]
fileList = [os.path.join(directory, f)
for f in fileList
if os.path.splitext(f)[1] in fileExtList]

def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]):
"get file info class from filename extension"
subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:]
return hasattr(module, subclass) and getattr(module, subclass) or FileInfo
return [getFileInfoClass(f)(f) for f in fileList]

if __name__ == "__main__":
for info in listDirectory("/music/_singles/", [".mp3"]):
print "\n".


See how much more readable that is? [smile]

Quote:
like for instance the book says things like __setitem__ and __parse are special attributes so why is he defining them?

They are special attributes in that their presence enables your class to access specific functionality. For instance, implementing __setitem__ allows your class instances to behave like a writeable dictionary.

Quote:
also I don't understand how everything works together and runs from this:

if __name__ == "__main__":
for info in listDirectory("/music/_singles/", [".mp3"]):
print "\n".

First of all, that code is probably wrong. It will simply print a blank newline for each element in the list. Secondly, every module in Python, including the currently executing one, has a name. You can access (read) that name by checking the __name__ property. The module invokved from the shell, etc, is named"__main__". You can check if your script is being executed from the command line this way, and - for example - cause your module to perform special validation steps in that case.

Share this post


Link to post
Share on other sites
The book won't copy the indents so I did a screenshot:

http://img74.imageshack.us/img74/2461/part1li2.jpg
http://img401.imageshack.us/img401/2884/part2wj1.jpg


it's 2 parts



Edit:

so the book's code is wrong?

also I already know about the __main__ and __name__ things

Share this post


Link to post
Share on other sites
pretty much everything....
when to use __init__
where/when to use .self in the class when defining things
when defining things...when do i need arguments
how to edit or things in the class outside the class


which is why i was asking for any good articles/books/anything about them

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this