How to store a function pointer in class?

Justin Sheehy dworkin at ccs.neu.edu
Thu Jan 20 14:06:40 EST 2000


"Sami Hangaslammi" <shang.remove_edu at st.jyu.fi.edu> writes:

> >>> class Test:
>         class_attribute = None
> 
> >>> def test_func(x):
>         print "test_func called with",x
> 
> >>> test_func
> <function test_func at b4e620>
> >>> Test.class_attribute = test_func
> >>> Test.class_attribute
> <unbound method Test.test_func>
> >>> Test.__dict__['class_attribute']
> <function test_func at b4e620>
> 
> Now I have a script where I need to store pointers to functions (among
> other things) to class attributes and retrieve them as ordinary
> functions. How do I do this

Well, 'pointers to functions' are not really a very Pythonic way to
think about such things.  A class or instance variable may be a
reference to a function object, though.

Since I'm not sure what you want to _do_ with your function pointers,
I'm not sure if I am answering your real question.  This may be helpful:

>>> class Test: 
...     class_attribute = None 
... 
>>> my_test = Test()
>>> def test_func(x): 
...     print "test_func called with",x 
... 
>>> Test.class_attribute = test_func # or my_test.class_attribute =
test_func
>>>                                  # depending on what you really
want
... 
>>> my_test.class_attribute()
test_func called with <__main__.Test instance at 80dff10>

Note that Python is not designed to have class methods, but rather
instance methods.  All functions defined inside a class expect to
receive an instance of the class as an implicit first argument.

>>> Test.class_attribute()
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: unbound method must be called with class instance 1st argument
>>> Test.class_attribute(my_test)
test_func called with <__main__.Test instance at 80dff10>
>>> my_test.class_attribute()
test_func called with <__main__.Test instance at 80dff10>

The first call here is an error.  The second and third are equivalent
to each other.

-Justin

 






More information about the Python-list mailing list