[Tutor] Dumb Subclassing question

Rich Krauter rmkrauter at yahoo.com
Thu Aug 5 15:05:17 CEST 2004


Andy Baker wrote:
> Hi all,
> 
> Please bear with me as I might have this hopelessly muddled. My attempts to
> learn OO through simple cases never turn out that simple...
> 
> I, like everyone else in the universe, am writing a prog to manipulate and
> organize mp3's...
> 
> The idea was to base it on Jason Orendorff 'path' module
> (http://www.jorendorff.com/articles/python/path/) and add some methods to
> the path object that are mp3 specific.
> 
> So I subclass the 'path' object as 'mp3path' and add some of my own methods.
> 
> Several of the methods in the original 'path' return more path objects so
> the methods I inherit from path also return path objects. I want my new
> methods to act on the returned objects.
> 
> An example:
> 
> myPath.files() returns a list of path objects
> 
> I have added a new method ID3tag to my MP3path class
> I want myMP3path.files to return a list of objects that can still access my
> ID3tag method.
> 
> Options that have occurred to me:
> 
> 1. Override every method in 'path' that returns paths with a wrapper method
> that converts them into mp3paths. This seems ugly, boring and pointless.
> 2. Forget subclassing and add methods directly into the path module source.
> This will be bad when a new version of 'path' comes along and also seems
> like cheating.
> 3. Add methods dynamically into the path object. (Is this 'decorator'?) I
> looked at the instancemethod function in the standard library 'new' module
> and this adds methiods to instances but not to classes so I would have to do
> this for every instance. 
> 4. Forget the whole OO thang and just use functions. (Looking more
> attractive by the minute ;-)
> 
>


Hi Andy,

I'd stick with classes. You might want to try composition (has-a) 
instead of inheritance (is-a).
One of the attributes of your MP3 object can be a path object; in 
addition you can add all the other attributes you need.

Basic idea (untested):

import your_module # substitute name of the module you're using

class MP3(object):
     def(__init__(self,filename):
         self.filename = filename
         # don't know name of class in module you reference
         # so I'm making it up. (Next line is composition.)
         self.pathobj = your_module.path_wrapper(filename)

         # do some work to get info out of mp3 headers
         self.ID3Tag = self.get_ID3Tag(filename)
         ...

if __name__ == '__main__:
     import os
     mp3root = '/path/to/mp3'
     # list to hold collection of MP3 objects
     mp3s = []
     for root,dirs,files in os.walk(mp3root):
         for f in files:
             mp3s.append(MP3('%s/%s'%(root,f))

     # now you have a collection of MP3 objects
     # and you can do stuff with it.
     ...
     ...

Good luck.

Rich


More information about the Tutor mailing list