object inheritance and default values

Kay Schluehr kay.schluehr at gmx.net
Fri Oct 14 22:31:48 CEST 2005


George Sakkis wrote:
> "Ron Adam" <rrr at ronadam.com> wrote:
>
> > I'm trying to implement simple svg style colored complex objects in
> > tkinter and want to be able to inherit default values from other
> > previously defined objects.
> >
> > I want to something roughly similar to ...
> >
> >     class shape(object):
> >          def __init__(self, **kwds):
> >               # set a bunch of general defaults here.
> >               self.__dict__.update(kwds)
> > def draw(self, x=0, y=0, scale=1.0):
> >               # draw the object
> >
> >     hello = shape(text='hello')
> >     redhello = hello(color='red')
> >     largeredhello = redhello(size=100)
> >     largeredhiya = largeredhello(text='Hiya!')
> >     largeredhiya.draw(c, 20, 50)
> >
> >
> > I think this will need to require __new__ or some other way to do it.
> > But I'm not use how to get this kind of behavior.  Maybe the simplest
> > way is to call a method.
> >
> >     redhello = hello.makenew( color='red' )
>
> Just name it '__call__' instead of makenew and you have the syntax sugar you want:
>
>     def __call__(self, **kwds):
>         new = self.__class__(**self.__dict__)
>         new.__dict__.update(kwds)
>         return new
>
> Personally I would prefer an explicit method name, e.g. 'copy'; hiding the fact that 'shape' is a
> class while the rest are instances is likely to cause more trouble than it's worth.
>
> George

Symmetry can be achieved by making shape a factory function of Shape
objects while those Shape objects are factory functions of other Shape
objects by means of __call__:

def shape(**kwds):
    class Shape(object):
          def __init__(self,**kwds):
              self.__dict__.update(kwds)

          def __call__(self, **kwds):
              new = self.__class__(**self.__dict__)
              new.__dict__.update(kwds)
              return new

    return Shape(**kwds)

Kay




More information about the Python-list mailing list