(beginners question) howto set self.field4.subfield8='asdf'?

Peter Otten __peter__ at web.de
Mon Feb 19 07:01:36 EST 2007


openopt at ukr.net wrote:

> Thx
> but is there any simpleir way, if using not class, but just struct (or
> something like that, MATLAB equivalent for that one)?
> I'm thinking of rewriting some optimization solvers (non-smooth,
> constrained, with (sub)gradients or patterns provided by user) to
> Python and I don't know currently is it possible to easy convert
> things like
> prob = [];
> prob.advanced.ralg.hs = 1 (so in this line all subfields are
> generating automatically in MATLAB or Octave)
> I have huge amount of such lines, and implementing separate class for
> each one is unreal.

Get used to thinking of a class as a lightweight construct written with
well-defined constraints rather than some know-it-all can-do-everything
unwieldy monster. You can of course use one class throughout

>>> class Struct:
...     def __init__(self, **kw):
...             self.__dict__.update(kw)
...
>>> a = Struct(f=42)
>>> b = Struct(x=1, y=2)
>>> a.f
42
>>> b.x, b.y
(1, 2)

but separate classes don't require much more effort and make your code both
more readable and more flexible.

Peter





More information about the Python-list mailing list