class declaration shortcut

Arnaud Delobelle arnodel at googlemail.com
Thu Mar 1 15:04:48 EST 2007


On Mar 1, 7:37 pm, Steven Bethard <steven.beth... at gmail.com> wrote:
> Arnaud Delobelle wrote:
> > On Mar 1, 4:01 pm, Steven Bethard <steven.beth... at gmail.com> wrote:
> >> Arnaud Delobelle wrote:
> > [...]
> >> This does pretty much the same thing as the recipe I posted:
>
> > Not at all.  My new_struct create returns a new class which is similar
> > to a C struct (notice the __slots__).  The recipe you refer to is
> > nothing more a class which can be initialised with some attributes. It
> > does not address the OP's question at all.
>
> >>      http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237
>
> Huh?  It uses __slots__ in almost exactly the same way.

I'm sorry I somehow got my hyperlinks mixed up and though you were
refering to

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

which was mentioned by someone else on this thread.  If I had seen
yours I wouldn't have posted this.  So my comment on you link was
completely erroneous as, as you are pointing out, the functionality of
my code snippet and your link are very similar.  Mine was only a proof
of concept bit of code, so yours is more polished.

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 because I though it would be a good idea to be able
not to initialise some of them at object instanciation.

--
Arnaud




More information about the Python-list mailing list