How to store a function pointer in class?

Neel Krishnaswami neelk at brick.cswv.com
Thu Jan 20 19:00:49 EST 2000


Sami Hangaslammi <shang.remove_edu at st.jyu.fi.edu> wrote:
> Justin Sheehy <dworkin at ccs.neu.edu> wrote in message
> news:vndaem01s1r.fsf at betelgeuse.ccs.neu.edu...
> 
> > A class or instance variable may be a reference to a function
> object, though.
> 
> If wish they could! The problem is that a class variable can NOT refer
> a function object, only an unbound method object. When a reference to
> a function object is stored in a class variable, it is instatly
> transformed into an unbound method (or so it seems).

That's what is happening, yes. However, you can store a function
object in an *instance* without running into any magical method
conversions.

So if you do this:

   >>> def foo():
   ...    return "Heya"
   ... 
   >>> class Bar:
   ...     def __init__(self, function):
   ... 	   self.function = function
   ... 
   >>> x = Bar(foo)
   ... 
   >>> x.function
   <function foo at 80d85e0>

things will work ok. You can also add members to an instance as
you need them, so if x is an instance of Bar, then 

  x.new_function = function_2

will also work.


Neel



More information about the Python-list mailing list