object inheritance and default values

George Sakkis gsakkis at rutgers.edu
Fri Oct 14 16:04:30 EDT 2005


"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





More information about the Python-list mailing list