[Tutor] overriding instance attributes with keywords

Matt Gregory matt.gregory at oregonstate.edu
Tue Aug 14 20:25:31 CEST 2012


On 8/14/2012 5:28 AM, eryksun wrote:
> On Tue, Aug 14, 2012 at 6:01 AM, eryksun <eryksun at gmail.com> wrote:
>>
>> Right, I overlooked classes with __slots__ and that override __new__
>> and other special methods. copy() is the better and more customizable
>> solution.
>
> If copying is good enough, then this should work:
>
> from copy import copy
>
> def copy_with_overrides(obj1, **kwds):
>      obj2 = copy(obj1)
>      for k, v in kwds.items():
>          if hasattr(obj2, k):
>              setattr(obj2, k, v)
>      return obj2

Thanks to you both for really helpful advice.  A quick follow-up 
question - would you want to create a deepcopy of obj1 in the above 
example if your obj1 contained other objects?  I think that Steven's 
class method gets around this?

thanks, matt



More information about the Tutor mailing list