class declaration shortcut

Steven Bethard steven.bethard at gmail.com
Thu Mar 1 15:11:50 EST 2007


Arnaud Delobelle wrote:
>>>>      http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237
[snip]
> Although I don't see the necessity of a metaclass: you could have
> 
> class Record(object):
>     def __init__(self, *vals):
>         for slot, val in zip(self.__slots__, vals):
>             setattr(self, slot, val)
>     # And the other methods
> 
> if you want positional slots initialisation.  I chose keyword
> arguments in mine

You could certainly do it that way, but note that the one with the 
metaclass not only allows *either* positional or keyword arguments, but 
also displays better help messages -- using the *vals or **vals code, 
help() will tell you something like:

     __init__(self, **vals)

while using the metaclass-generated __init__, help() will tell you the 
more informative:

     __init__(self, name)

(Or whatever signature is appropriate given the __slots__.) So no, it's 
not necessary, but it does have a few advantages.

STeVe



More information about the Python-list mailing list