Factory for Struct-like classes

Michele Simionato michele.simionato at gmail.com
Wed Aug 13 13:29:34 EDT 2008


On Aug 13, 6:43 pm, eliben <eli... at gmail.com> wrote:
> Hello,
>
> I want to be able to do something like this:
>
> Employee = Struct(name, salary)
>
> And then:
>
> john = Employee('john doe', 34000)
> print john.salary
>
> Basically, Employee = Struct(name, salary) should be equivalent to:
>
> class Employee(object):
>   def __init__(self, name, salary):
>     self.name = name
>     self.salary = salary
>
> Ruby's 'Scruct' class (http://ruby-doc.org/core/classes/Struct.html)
> does this. I suppose it can be done with 'exec', but is there a more
> Pythonic way ?
>
> Thanks in advance
>
> P.S.  I'm aware of this common "pattern":
>
> class Struct:
>     def __init__(self, **entries):
>         self.__dict__.update(entries)
>
> Which allows:
>
> john = Struct(name='john doe', salary=34000)
> print john.salary
>
> But what I'm asking for is somewhat more general.


NamedTuples: http://code.activestate.com/recipes/303439/



More information about the Python-list mailing list