Re: class declaration shortcut
- From: Steven Bethard <steven.bethard@xxxxxxxxx>
- Date: Wed, 28 Feb 2007 15:09:02 -0700
Luis M. González wrote:
On Feb 28, 6:21 pm, Steven Bethard <steven.beth...@xxxxxxxxx> wrote:[snip]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
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
.
- References:
- class declaration shortcut
- From: Luis M. González
- Re: class declaration shortcut
- From: Steven Bethard
- Re: class declaration shortcut
- From: Luis M. González
- class declaration shortcut
- Prev by Date: Re: How to check for remaining hard drive space in Windows?
- Next by Date: Re: Python Source Code Beautifier
- Previous by thread: Re: class declaration shortcut
- Next by thread: convert many excel files to pdf in batch
- Index(es):
Relevant Pages
|