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

Stargaming stargaming at gmail.com
Mon Feb 19 11:19:24 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)?

Use this::

 >>> A = type('', (), {})
 >>> a = A()
 >>> a
<__main__. object at 0x009E8490>
 >>> a.foo = 42
 >>> a.foo
42

But perhaps using this (with a better name) would be more sensible 
(according to readability)::

 >>> class B: pass
...
 >>> b = B()
 >>> b.foo = 42
 >>> b.foo
42

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

Perhaps something like this would be suitable::

 >>> class Autocreating(object):
...   def __getattr__(self, attr):
...     if hasattr(self, attr)
...       setattr(self, attr, Autocreating())
...     return getattr(self, attr)
...
 >>> a = Autocreating()
 >>> a.foo = 42
 >>> a.foo
42
 >>> a.hello.world = 23
 >>> a.hello
<__main__.Autocreating object at 0x...>
 >>> a.hello.world
23

But this is perhaps not a good way because it's way too implicite.

> I have huge amount of such lines, and implementing separate class for
> each one is unreal.

You don't have to implement a separate class for *each one*. Use one 
class for every attribute, you can reuse it. But perhaps something like 
a dict is better for your purposes, anyways.

HTH,
Stargaming



More information about the Python-list mailing list