instance creatiion as an "event"

Alex Martelli aleax at aleax.it
Tue Apr 22 16:12:04 EDT 2003


Arthur wrote:

> Alex:
> 
>>I don't understand this. When you call:
> 
>>p = TestPoint(args)
>>p.redraw()
> 
>>it's EXACTLY AS IF TestPoint.__init__'s very last statement was
> 
>>self.redraw()
> 
> Standalone, yes.  But, unless I'm missing something, the effects in an
> inheritance chain is different. If I inherit from TestPoint, and need to
> call TestPoint.__init__ in the Point_Child.__init__ to pick up
> initilization routines common to the chain, I will now unavoidably be
> calling TestPoint's
> redraw method before I call Point_Child's.

Not with the once-habitual Python idiom for that purpose.  Try it!

class TestPoint:
    def __init__(self):
        self.tp = 23
        self.redraw()
    def redraw(self):
        print 'TestPoint.redraw', self.tp

class PointChild(TestPoint):
    def __init__(self):
        self.pc = 42
        TestPoint.__init__(self)
    def redraw(self):
        print 'PointChild.redraw', self.tp, self.pc

p = PointChild()


and not with super either, in the new object model:


class TestPoint(object):
    def __init__(self):
        self.tp = 23
        self.redraw()
    def redraw(self):
        print 'TestPoint.redraw', self.tp

class PointChild(TestPoint):
    def __init__(self):
        self.pc = 42
        super(PointChild, self).__init__()
    def redraw(self):
        print 'PointChild.redraw', self.tp, self.pc

p = PointChild()


Of course, this relies on the ability of being able to call the superclass's 
__init__ at the APPROPRIATE point in the subclass's __init__ ...!  If you
cannot rely on that, e.g. because implementation issues are just too
intricate, use the wrapper factory functions I suggested in the previous 
post (or similar but more sophisticated approaches based e.g. on a
custom metaclass!).


  When the main reason I am
> inheriting from TestPoint is to override its redraw method, and in fact to
> avoid calling it.  If TestPoint has attributes that Point_Child does not
> that are referenced in its redraw method, I will have an attribute error
> on the calling of TestPoint's redraw form Point_Child.

I don't know what you're saying.  TestPoint is the baseclass.  How can
it have attribute that its subclass PointChild lacks?!?!?!

I'm not just thinking of the theoretical horror of that.  In practice
too, instance attributes of an instance of TestPoint will be set in
TestPoint.__init__ -- if you call that from PointChild.__init__, in
whatever way (as you normally should), then the instance WILL have
those attributes set, period.

> suggestion as to working with the condition
> 
> if hasattr(sys, 'ps1')

That's for when you want to do different things in interactive
_sessions_ than in programs (doing different things at an interactive
_prompt_ is subtler -- and perhaps best achieved by wrappers, as
per my previous post).


Alex





More information about the Python-list mailing list