[Tutor] Question on classes/instances

Negroup - negroup at gmail.com
Wed Aug 10 03:46:02 CEST 2005

Hi, Sorry for the subject a bit generic. This question comes from a
simple program I'm doing. I could have a working solution, but
considering my inexperience, I'm just asking if my approach is

This is a simple class to manage (actually to create and save)
categories of things. Categories are represented as directories, while
descriptions of categories are stored inside a file called
.description inside the category directory. Look at the code..

class Category:
        def __init__(self, name=None, description=None):
                self.description = description
                if name:
                        self.name = name
                        return 'Value expected'

        def save(self):
                from os import access, F_OK, mkdir

                path = 'categories/%s' % self.name
                if access(path, F_OK):
                        return 'Category already present'
                        if self.description:
                                f = file('%s/.description' % path, 'w')

and this is a simple function to get a list of categories, inside the
same module of Category:
def get_categories():
        from os import listdir
        return listdir('categories')

I would instead, that get_categories returns a list of instances of
Category class instead of a list of strings, so that I can handle
categories with proper APIs. I found this way:

def get_categories():
        from os import listdir
        # return listdir('categories')
        path = 'categories'
        categories = [Category(name, file('%s/%s/.description' %
(path, name)).read()) for name in listdir('categories')]
        return categories

Is it a good way to solve the problem? Otherwise, I would be glad if
you could propose better solutions.

Thanks for any clarification.

More information about the Tutor mailing list