Factory for Struct-like classes
Larry Bates
larry.bates at websafe.com`
Thu Aug 14 11:19:06 EDT 2008
eliben 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.
>
>
That's about as "general" as it gets ;-). It works for any number/type of
attribute. I would probably make it a new-style class by subclassing object,
but for simulating a generic row container, this is quite good. You might
extend it with a __str__ method, __len__ method, make it an iterator, etc.
but that is quite easy.
-Larry
More information about the Python-list
mailing list