Automatic constructors

Antonio Cuni TOGLIMIcuni at
Sat Oct 19 02:30:25 CEST 2002

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 

def constructor(*fields):
    numFields = len(fields)
    def __init__(self, *args):
        if len(args) != numFields:
            raise TypeError(
                '__init__ takes exactly %d arguments (%d given)' %
                (numFields + 1, len(args))                )

        for field, arg in zip(fields, args):
            setattr(self, '_%s' % field, arg)

    return __init__

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? Eg: 

__init__ = constructor(x,y,z)

ciao Anto
"Computer science is not about computers any more than astronomy
is about telescopes." -- EW Dijkstra

More information about the Python-list mailing list