On Mon, Aug 13, 2012 at 3:13 PM, Gregory, Matthew
<[email protected]> 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
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor