class declaration shortcut
Steven Bethard
steven.bethard at gmail.com
Thu Mar 1 14:37:42 EST 2007
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. If you just
s/Struct/Record in your ``new_struct`` function, you'll get essentially
the same behavior, except that if you use the recipe, you'll get an
__init__ that handles positional arguments, and displays better help::
>>> def new_struct(name, *slots):
... return type(name, (Struct,), {'__slots__': slots})
...
>>> Person = new_struct('Person', 'name')
>>> Person('Bob')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: __init__() takes exactly 1 argument (2 given)
>>> Person(name='Bob')
Person(name='Bob')
>>> help(Person.__init__)
Help on method __init__ in module __main__:
__init__(self, **vals) unbound __main__.Person method
>>> def new_struct(name, *slots):
... return type(name, (Record,), {'__slots__': slots})
...
>>> Person = new_struct('Person', 'name')
>>> Person('Bob')
Person(name='Bob')
>>> help(Person.__init__)
Help on method __init__:
__init__(self, name) unbound records.Person method
Maybe I'm not understanding you?
Steve
More information about the Python-list
mailing list