class declaration shortcut

Steven Bethard steven.bethard at gmail.com
Thu Mar 1 11:01:36 EST 2007


Arnaud Delobelle wrote:
> On Feb 28, 7:26 pm, "Luis M. González" <luis... at gmail.com> 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)
>>
>> I tried something like this, but it's nothing close to what I'd like:
>>
>> def klass(table, *args):
>>         cls = new.classobj(table, (), {})
>>         for i in args:
>>                 setattr(cls, i, i)
>>         return cls
>>
>> But this above is not what I want.
>> I guess I should find a way to include the constructor code inside
>> this function, but I don't know if this is possible.
>> Also, I wonder if there is a way to use the variable name in order to
>> create a class with the same name (as in "Person"above).
>>
>> Well, if anyone has an idea, I'd like to know...
>>
>> Luis
> 
> Perhaps something like:
> 
> class Struct(object):
>     def __init__(self, **vals):
>         for slot, val in vals.iteritems():
>             setattr(self, slot, val)
>     def __repr__(self):
>         return "%s(%s)" % (type(self).__name__,
>             ", ".join("%s=%s" % (slot, repr(getattr(self, slot))) for
> slot in self.__slots__ if hasattr(self, slot)))
> 
> def new_struct(name, *slots):
>     return type(name, (Struct,), {'__slots__': slots})
> 
> 
> Then you can do:
> 
>>>> Point = new_struct('Point', 'x', 'y')
>>>> p=Point(x=1, y=2)
>>>> p
> Point(x=1, y=2)
>>>> p.x
> 1
>>>> p.y
> 2
>>>> p.x=7
>>>> p
> Point(x=7, y=2)
>>>> Person = new_struct('Person', 'name', 'tel', 'email')
>>>> jack = Person(name='Jack')
>>>> jack
> Person(name='Jack')
>>>> jack.tel='555-132'
>>>> jack
> Person(name='Jack', tel='555-132')

This does pretty much the same thing as the recipe I posted:

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

Note that your approach requires repetition of the 'Person' and quotes 
around each attribute name, which the OP complained about. The recipe at 
least gets rid of the repetition of 'Person'.

You might also want to check out Raymond Hettinger's NamedTuple recipe:

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

STeVe



More information about the Python-list mailing list