post init call

Peter Otten __peter__ at web.de
Mon Jun 18 06:45:57 EDT 2012


Prashant wrote:

> class Shape(object):
>     def __init__(self, shapename):
>         self.shapename = shapename
>         
>         
>     def update(self):
>         print "update"
> 
> class ColoredShape(Shape):
>     def __init__(self, color):
>         Shape.__init__(self, color)
>         self.color = color
>         print 1
>         print 2
>         print 3
>         self.update()
> 
> User can sub-class 'Shape' and create custom shapes. How ever user must
> call 'self.update()' as the last argument when ever he is sub-classing
> 'Shape'. I would like to know if it's possible to call 'self.update()'
> automatically after the __init__ of sub-class is done?

I don't think so. You could however shuffle things around a bit:

class Shape(object):
    def __init__(self, shapename, *args, **kw):
        self.shapename = shapename
        self.init(*args, **kw)
        self.update()
    def init(self, *args, **kw):
        pass
    def update(self):
        print "update"

In that constellation you would override init(), not __init__():

class ColoredShape(Shape):
    def init(self, color, **kw):
        self.color = color
        print 1
        print 2
        print 3





More information about the Python-list mailing list