[Tutor] Subclassing data attributes

Kent Johnson kent37 at tds.net
Fri Nov 4 14:28:22 CET 2005

Jan Eden wrote:
> Not exactly. My current setup bundles all data attributes in a single
> module Data containing a single class for each object. So in my main
> module (Show), I define:> 
> class Page(Data.Page):
>     ...
> and Data contains:
> class Base:
>     children = 'xyz'
>     children_query = 'SELECT...'
> class Page:
>     children = 'something'
>     own_type = 'somethingelse'
>     populate_query = "SELECT ..."
>     index_link = "<p>..."
>     ...
> So I can use self.children_query for an object of class Show.Page to
> get the data attribute defined in class Data.Base.
> But since there are many data attributes, I'd like to use things like:
> self.templates['index_link']
> self.templates['child_link']
> self.queries['populate']
> or
> self.Templates.index_link
> self.Templates.child_link
> self.Queries.populate

OK I'll try again. I still don't understand why you don't like using straight class attributes - is it to keep the size of the class namespace smaller?

I'm also not sure if you want to be able to access Base.children and Page.children from a subclass of Page. If not, then you can use a hierarchical dictionary to do what you want. How about this?

import UserDict

class ChainDict(UserDict.DictMixin):
    ''' A dict that will delegate failed lookups to a parent '''
    def __init__(self, parent=None):
        self._dict = dict()
        self._parent = parent
        # __setitem__() and __delitem__() delegate to self._dict
        self.__setitem__ = self._dict.__setitem__
        self.__delitem__ = self._dict.__delitem__

    def __getitem__(self, key):
            return self._dict[key]
        except KeyError:
            if self._parent is not None:
                return self._parent[key]

    def keys(self):
        keys = self._dict.keys()
        if self._parent is not None:
class Base:
    templates = dict()
    templates['children'] = 'xyz'
    templates['children_query'] = 'SELECT * from Base'

class Page(Base):
    templates = ChainDict(Base.templates)
    templates['children'] = 'something'
    templates['own_type'] = 'somethingelse'
    templates['populate_query'] = "SELECT * from Page"
    templates['index_link'] = "<p>..."

b = Base()
print b.templates['children']
print b.templates['children_query']

p = Page()
print p.templates['children']
print p.templates['children_query']
print p.templates['index_link']


PS Please reply on list.


More information about the Tutor mailing list