How to store a function pointer in class?

Sami Hangaslammi shang.remove_edu at st.jyu.fi.edu
Thu Jan 20 15:58:15 EST 2000


Justin Sheehy <dworkin at ccs.neu.edu> wrote in message
news:vnd66wo1nz2.fsf at betelgeuse.ccs.neu.edu...
> You could store the function inside a mutable class data member.

Yeah, I figured this out myself, but it still seems like an
unneccessary and ugly hack. So far the best I could come up with was
to make a wrapper class for a function. i.e.

class func:
    def __init__(self, f):
        self.f = f
    def __call__(self,*args,**keyw):
        return apply(self.f, args, keyw)

Now I can use:

>>> Test.class_attribute = func(test_func)
>>> Test.class_attribute(1)
test_func called with 1
>>> f = Test.class_attribute.f

Alternatively you could add __doc__, __code__ etc. members and pass
the func object to any code requiring a function.

> For instance:
>
> >>> class Test:
> ...   class_attribute = []
>
> >>> def test_func(x):
> ...     print "test_func called with",x

Thanks for your ideas!

--
Sami Hangaslammi
shang (at) st (dot) jyu (dot) fi





More information about the Python-list mailing list