How to store a function pointer in class?

Skip Montanaro skip at mojam.com
Thu Jan 20 15:04:34 EST 2000


    >> A class or instance variable may be a reference to a function object,
    >> though.

    Sami> If wish they could! The problem is that a class variable can NOT
    Sami> refer a function object, only an unbound method object. 

Check out the optional new module (distributed with Python, but not enabled
by default, at least not in the past), especially new.instancemethod.  It
takes a function object, an instance and a class and returns the appropriate
goody.  I've never had occasion to use it in a real situation, but the
following trivial code works:

    import new

    class Foo:
	def addmethod(self, name, func):
	    setattr(foo, name, new.instancemethod(func, self, Foo))

    foo = Foo()

    def sqr(self, a):
	return a*a

    foo.addmethod("sqr", sqr)

    print foo.sqr(4)

Cheers,

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/
847-971-7098




More information about the Python-list mailing list