Hi all,
I'm trying to create a new instance from an existing instance with attributes
of the new instance allowed to be overwritten by keyword parameters. I'm
guessing I'm not doing this in the most efficient manner.
class Spam:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "%s: (%d,%d)" % (self.__class__.__name__, self.a, self.b)
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'])
s1 = Spam(4, 10)
s2 = new_with_overrides(s1)
s3 = new_with_overrides(s1, a=3)
s4 = new_with_overrides(s1, b=7)
This works but it doesn't seem very extendable if new attributes are added to
Spam. I know that I can make new_with_overrides a method of Spam and that may
simplify things a bit (e.g. using __dict__).
thanks, matt
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor