[Python-Dev] reducing self.x=x; self.y=y; self.z=z boilerplate code
Nick Coghlan
ncoghlan at gmail.com
Sat Jul 2 02:14:44 CEST 2005
Jp Calderone wrote:
> If you use vars(self).update(locals()), it even looks halfway
> pleasant ;) I'm not sure what python-dev's current opinion of
> vars(obj) is though (I'm hoping someone'll tell me).
>
> Of course, both of these fall over for __slots__'ful classes. It'd
> be nice if there were a general way to deal with attributes of an
> instance, regardless of the implementation details of its memory
> layout.
That's where PJE's more generic approach comes in:
def initialize(ob, args, excluded=['self']):
for k in excluded:
if k in args:
del args[k]
for k, v in args.items():
setattr(ob,k,v)
class grouping:
def __init__(self, x, y, z):
initialize(self, locals())
Or, one could have a look at the 'namespace' module, which came out of
the last pre-PEP covering this kind of area:
http://namespace.python-hosting.com/
'Record' is particularly interesting from an auto-initialisation point
of view (the class attributes define the expected instance
attributes). Although I may be a little biased, since I wrote that
class. . .
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.blogspot.com
More information about the Python-Dev
mailing list