[Tutor] overriding instance attributes with keywords
eryksun
eryksun at gmail.com
Tue Aug 14 14:28:41 CEST 2012
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
However, I apologize for sidetracking you if you need __init__ to run
(possibly creating new instances of attributes instead of getting
copied references). That really should be a classmethod as Steve
suggests (or simple a regular method and use cls = self.__class__),
and you'll need to keep it in sync with any changes you make to
__init__. A generic function can't know how to call the constructor.
Even if you use inspect.getfullargspec(), there's no guarantee every
argument will have a corresponding object attribute with the same name
or that the current value is the one __init__ needs -- not unless you
design it that way.
More information about the Tutor
mailing list