At 03:59 PM 7/1/2005 -0700, Ralf W. Grosse-Kunstleve wrote:
>Hi,
>
>I often find myself writing:
>
> class grouping:
>
> def __init__(self, x, y, z):
> self.x = x
> self.y = y
> self.z = z
>
>I hate it, and every time I show this to a Python newcomer I get that
>skeptic look. How about this for a change?
>
> class grouping:
>
> def __init__(self, .x, .y, .z):
> pass
This extends to any number of arguments:
class grouping:
def __init__(self, x, y, z):
self.__dict__.update(locals())
del self.self
Or if you prefer a more generic approach:
def initialize(ob, args):
if 'self' in args:
del args['self']
for k, v in args.items():
setattr(ob,k,v)
class grouping:
def __init__(self, x, y, z):
initialize(self, locals())
There's really no need for special syntax here, if your goal is simply to
reduce boilerplate.
>I'll write a PEP if I hear a few voices of support.
-1; there are lots of good solutions for this. For me, I usually have a
base class with something like this:
def __init__(self, **kw):
for k, v in kw.items():
if not hasattr(self.__class__, k):
raise TypeError("%s has no %r attribute" % (self.__class__,k))
else:
setattr(self,k,v)
And then subclasses define their attributes and defaults using class
attributes, properties, or other descriptors.
>(Otherwise I'll stick to my "adopt_init_args" workaround:
>http://phenix-online.org/cctbx_sources/libtbx/libtbx/introspection.py
>which does a similar job but doesn't look as elegant and is also
>quite inefficient).
There are more efficient solutions, especially __dict__.update().
_______________________________________________
Python-Dev mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com