(beginners question) howto set self.field4.subfield8='asdf'?
Peter Otten
__peter__ at web.de
Mon Feb 19 05:04:19 EST 2007
openopt at ukr.net wrote:
> I have
> class A:
> def __init__(self, objFun, x0):
> #(I want to have self.primal.f = objFun)
> #both
> self.primal.f = objFun
> #and
> self.primal = None
> self.primal.f = objFun
None is a singleton, so if Python were to allow the above f would always be
the objFun of the last created A instance.
> yields error
> what should I do?
Make a dedicated Primal class:
>>> class Primal:
... pass
...
>>> class A:
... def __init__(self, fun, x0):
... self.primal = Primal()
... self.primal.f = fun
...
>>> def square(x): return x*x
...
>>> a = A(square, 42)
>>> a.primal.f
<function square at 0x401d609c>
Even better, because it makes no assumptions about the internal layout of
Primal:
class Primal:
def __init__(self, f):
self.f = f
...
self.primal = Primal(fun)
...
Peter
More information about the Python-list
mailing list