overriding method that returns base class object
Scott David Daniels
Scott.Daniels at Acm.Org
Tue Feb 17 11:48:36 EST 2004
Stuart McGraw wrote:
> "Paul Rubin" <http://phr.cx@NOSPAM.invalid> rote in message news:7xwu6mmm3v.fsf at ruckus.brouhaha.com...
>>...
>>class B(A):
>> def __init__(self, *args, **kwds):
>> self.newprop = 99
>> self.wrapped_A = A(*args, **kwds)
>> def a(self):
>> x = B()
>> x.wrapped_A = A.a(self.wrapped_A)
>> return # I want x to be a B, i.e have b() and .newprop.
>> def __getattr__(self, attr):
>> # delegate all inherited operations to the wrapped A object
>> return A.__getattr__(self.wrapped_A, attr)
>>
>>You might also be able to do something crazy, like change A's metaclass
>>so that its __new__ operation can make a B under certain circumstances.
>
> Ahhhh.... I did not know about delegation. I do now, thanks.
> A minor disadvantage is that, because I also delegate __setattr__
> all the instance variable have to be assigned in the form
> self.__dict__['var'], rather than self.var (as I discovered the hard
> way). Ugly, but I can live with it. Thanks again.
If you can separate the names, you can do something like:
class B(object):
def __init__(self, *args, **kwargs):
self._a = A(*args, **kwargs)
self.newprop = 99
def __setattr__(self, name, val):
if name.startswith('_') or name == 'newprop':
self.__dict__[name] = val
else:
setattr(self._a, name, val)
def getattr(self, name):
return getattr(self._a, name)
--
-Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list