class declaration shortcut

Steven Bethard steven.bethard at gmail.com
Wed Feb 28 17:09:02 EST 2007


Luis M. González wrote:
> On Feb 28, 6:21 pm, Steven Bethard <steven.beth... at gmail.com> wrote:
>> How about something like::
>>
>>      class Person(Record):
>>          __slots__ = 'name', 'birthday', 'children'
>>
>> You can then use the class like::
>>
>>      person = Person('Steve', 'April 25', [])
>>      assert person.name == 'Steve'
>>      assert person.birthday == 'April 25'
>>      assert not person.children
>>
>> Is that what you were looking for?  If so, the recipe for the Record
>> class is here:
>>
>>      http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502237
[snip]
> Hmmm... not really.
> The code above is supposed to be a shorter way of writing this:
> 
> class Person:
>     def __init__(self, name, birthday, children):
>         self.name = name
>         self.birthday = birthday
>         self.children = children
> 
> So the purpose of this question is finding a way to emulate this with
> a single line and minimal typing.

That __init__ is exactly what was generated in my example above.  So 
you're mainly objecting to using two-lines? You can make it a one-liner 
by writing::

     class Person(Record): __slots__ = 'name', 'birthday', 'children'

> 1) How to get the variable name (in this case "Person") become the
> name of the class without explicity indicating it.

The only things that know about their own names are class statements 
(through metaclasses) so you can't really do it without a class 
statement of some sort (which means you'll have to use two lines).

> 2) How to enter attribute names not enclosed between quotes. The only
> way I can do it is by entering them as string literals.

If you're really bothered by quotes, a pretty minimal modification to 
the recipe could generate the same code from:

     class Person(Record): slots = 'name birthday children'

STeVe



More information about the Python-list mailing list