Idea about method parameters
Markus Schaber
markus at schabi.de
Mon Sep 24 18:38:54 EDT 2001
Wolfgang Grafen <wolfgang.grafen at marconi.com> schrub:
> Don't think you cannot do it already!
>
>>>> class Autoinit:
> ... def __init__(self,**a):
> ... self.__dict__.update(a)
> ...
>>>> a=Autoinit(a=1,b=2,c=3)
>>>> a.a
> 1
>>>> a.b
> 2
>>>> a.c
> 3
>
>>>> class A(Autoinit):
> ... def __call__(self):
> ... print self.a,self.b,self.c
> ...
>>>> a=A(a=1,b=2,c=3)
>>>> a()
> 1 2 3
Nice idea, especially when your classes mainly work as Attribute
Containers, but I have some objections:
1. This way you don't have any control what the caller sets - he just
might set anything. Okay, in Python, he really can do anything he wants
with your object, but sometimes it is helpful to have some hints by the
compiler or interpreter, especially to find typos (useful when you have
lots of long-named parameters). And if you have to test the contents of
**a "by hand", you don't save any work, and it gets less readable.
Assume you have more than one place in your program where that
constructor/method gets called, one of them has a typo in one parameter
name, and so you occasionally corrupt parts of your database. Or the
misspelled parameter sets an attribute that is never looked at again,
and all the following code uses the old value from the correctly
spelled attribute that was created before (only applies to
non-constructor methods)
2. Messing with __dict__ seems to be a "dirty hack" in my eyes, and
doesn't produce readable code (you cannot exactly guess what gets
changed in the object, especially when it isn't the constructor, but
another method.)
3. You kick the possibility to give positional parameters
4. You kick the possibility to give default value
5. You have to explicitly document what your caller can give you - a
"normal" parameter list in a def: with sensible parameter names (and
maybe useful default values) usually is a very useful bit of
documentation, especially when you know the main idea and just forgot
some specific spelling detail or so.
markus
--
"The strength of the Constitution lies entirely in the determination of
each citizen to defend it. Only if every single citizen feels duty
bound to do his share in this defense are the constitutional rights
secure." -- Albert Einstein
More information about the Python-list
mailing list