Default attribute in base class precludes delegation

Gabriel Genellina gagenellina at softlab.com.ar
Fri Dec 19 01:32:42 EST 2003


At 19/12/2003 00:56, you wrote:

> > My workaround was to *really* set an instance attribute 'bar' in 
> Derived, and
> > try to ensure that it's always in sync with Worker:
> >
> >          def __init__(self, worker):
> >                  self.worker = worker
> >                  self.bar = worker.bar
> >
> >          def setBar(self, bar):
> >                  self.worker.bar = bar
> >                  self.bar = bar
> >
> > This works if a) all people always use setBar on Derived, and b) no one
> > assigns to worker.bar directly.
>
>Hm.  Maybe you can define a __setattr__ for Derived, then.  Something like
>(untested):
>
>   def __setattr__(self, name, value):
>       if name == 'bar':
>           self.worker.bar = bar
>       self.__dict__[name] = value
>
>That way, people can assign to d.bar (where d is an instance of Derived)
>directly, and it will/should still keep the sync.

Yes, thanks, that would work for all assignments to d.bar
But item b) is still a problem: anyone who has a reference to a Worker 
instance could write w.bar = xxx and things would go out of sync...
Maybe I could make Worker aware of its container somehow (ouch... avoiding 
a circular reference?) and update it whenever w.bar is changed... But 
unless someone gives a better answer, I will just shout aloud all people 
involved: DONT DO THINGS THIS WAY!!! and hope nobody forgets it...


Gabriel Genellina
Softlab SRL






More information about the Python-list mailing list