[Tutor] overriding instance attributes with keywords

eryksun eryksun at gmail.com
Mon Aug 13 23:16:13 CEST 2012


On Mon, Aug 13, 2012 at 3:13 PM, Gregory, Matthew
<matt.gregory at oregonstate.edu> wrote:
>
> I'm trying to create a new instance from an existing instance

> def new_with_overrides(s1, **kwargs):
>     new_params = {'a': s1.a, 'b': s1.b}
>     for (k, v) in kwargs.iteritems():
>         if k in new_params:
>             new_params[k] = v
>     return Spam(new_params['a'], new_params['b'])

> This works but it doesn't seem very extendable if new attributes are added to Spam.

In general instance attributes won't map to __init__ arguments. You
can create a new instance by calling  __new__. Then update from the
old dict and add in override attributes.

def new_with_overrides(obj1, **kwds):
    obj2 = obj1.__new__(obj1.__class__)
    obj2.__dict__.update(obj1.__dict__)
    for k, v in kwds.items():
        if k in obj2.__dict__:
            obj2.__dict__[k] = v
    return obj2


More information about the Tutor mailing list