class declaration shortcut

Arnaud Delobelle arnodel at googlemail.com
Thu Mar 1 06:26:28 EST 2007


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')
>>>

etc...

Of course that's if you want a c-like struct. Otherwise there's not
much point at all!

--
Arnaud





More information about the Python-list mailing list