[Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference?
andreengels at gmail.com
Fri Jan 16 14:05:15 CET 2009
On Fri, Jan 16, 2009 at 1:51 PM, Vicent <vginer at gmail.com> wrote:
> I am posting this question to two Python forums: Tutor and Python(x,y).
> In the case of Tutor , I think it's the right place to ask questions for
> a newbie like me.
> In the case of Python(x,y) Discussion Group , I am posting also because I
> think I am addressing a specific group of Python users that probably
> previously dealed with the same problems I do now. Anyway, let me know if
> it's a good idea to keep on doing this in the future.
> This question is about how to define classes or objects (or data structures)
> I need to use, and how to do it in an efficient way.
> I want to define an object or data structure called "Problem".
> That "problem" has to contain, somehow, a property or element called
> "function" which, in fact, I would like it to be a function, or a "pointer"
> to a function.
> For example, if "prob" is a "Problem" object, I would like to be able to
> do something like this:
> # call the function in prob, and store the result in "x" :
> x = prob.function( arguments/variables required by the function )
> Does it makes any sense? Which would it be the right (meaning efficient but
> still object-oriented-programming-compliant) way to do it?
> I mean, if I store "a whole function" within each "Problem" object (assuming
> it can be done in Python), each Problem object would be consuming lot of
> memory (wouldn't it?). Maybe it would be better just to store a kind of
> "pointer" to the function within the "problem" object, so the object would
> be "lighter". The function would be then defined outside the object, as
> Can you give me some hint about this?
In fact, this can be done in Python very easily, see the following
>>> class test(object):
>>> test1 = test()
>>> test2 = test()
>>> def double(x):
>>> def square(x):
>>> test1.f = double
>>> test2.f = square
André Engels, andreengels at gmail.com
More information about the Tutor