Automatic constructors

Jimmy Retzlaff jimmy at retzlaff.com
Sat Oct 19 07:27:53 EDT 2002


Antonio Cuni wrote:
> In writing my code I often need to write __init__ methods like this:
>
> def __init__(self, x,y,z):
>     self._x = x
>     self._y = y
>     self._z = z
>
> The number of fields and their names vary from class to class, of
course; 
> I'd like to find a way for automatize this process: by now I have
write 
> this:
...
> So I can write:
>
> class foo:
>     __init__ = constructor('x', 'y', 'z')
>
> It works, but I don't like to use strings to specify fields name: is 
> there any way to use "plain" names?
...

I just submitted a recipe to the Python Cookbook demonstrating the
approach I use:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157572

I don't entirely replace the constructor because I often want to do
additional work. Also the approach can be useful in methods other than
__init__.

Jimmy




More information about the Python-list mailing list