parent-child object design question

manstey manstey at csu.edu.au
Wed Jan 31 18:09:29 EST 2007


Thanks for your input. Here is my next version, which works very well,
but for one problem I explain below:

class CacheProperty(object):
    def __init__(self, insCacheClass, name):
        self.Name = name
        self._bind_to_parent(insCacheClass)
        self.__parent = insCacheClass
        self.__pyValue = self.__parent.get(name)

    def _bind_to_parent(self, parent):
        setattr(parent, self.Name, self)

    def get(self):
        return self.__pyValue

    def set(self, val):
        self.__parent.set(self.Name, val)
        self.__pyValue = val # Set in wrapper's copy

    Value = property(get, set)

    def __repr__(self):
        return str(self.Value)
    def __str__(self):
        return str(self.Value)


class CacheClass(object):
    def __init__(self, obj):
        self.__data = obj

    def getOref(self):
        return self.__data
    def __repr__(self):
        return 'self.__data'
    def __str__(self):
        return str(self.__data)
    def __getattr__(self, attr):
        return getattr(self.__data, attr)

Our code works fine as follows (oref is in-memory version of Cache oo-
dbase class, and is an old-style class that comes with set and get and
run_obj_method methods):
>>> insCacheClass = CacheClass(oref)
>>> insCacheProperty = CacheProperty(insOref,'Chapter')
>>> print insOref.Chapter.Value
5
>>> print insOref.Chapter.Name
'Chapter'
>>> insOref.Chapter.Value=67
>>> print insOref.Chapter
67

However, the problem is now that I can also write:
>>> insOref.Chapter=67
but we want to disallow this, as insOref.Chapter must remain =
insProperty

We add various other instances of CacheProperty to the insOref as
well, btw.

So any idea how to prohibit this, and can the class code above be
improved? Does it matter that each instance of CacheProperty contains
self.__parent? Does it actually "contain" the parent (I realise this
is not 'parent' in usual python lingo - what would be a better term?),
or is self.__parent simply point to it somehow? I don't understand
this part of python at all!

Thanks, you are being a great help in our development.




More information about the Python-list mailing list