class declaration shortcut

Luis M. González luismgz at gmail.com
Wed Feb 28 16:53:37 EST 2007


On Feb 28, 6:21 pm, Steven Bethard <steven.beth... at gmail.com> wrote:
> Luis M. González wrote:
> > I've come across a code snippet inwww.rubyclr.comwhere they show how
> > easy it is to declare a class compared to equivalent code in c#.
> > I wonder if there is any way to emulate this in Python.
>
> > The code is as follows:
>
> > Person = struct.new( :name, :birthday, :children)
>
> 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
>
> STeVe



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.

There are a few problems here:
1) How to get the variable name (in this case "Person") become the
name of the class without explicity indicating it.
2) How to enter attribute names not enclosed between quotes. The only
way I can do it is by entering them as string literals.

It's not that I desperately need it, but I'm just curious about it...

Luis





More information about the Python-list mailing list