keeping a ref to a non-member function in a class
gnb at itga.com.au
Tue Aug 16 09:57:39 CEST 2005
I'm building a class hierarchy that needs to keep as a class variable a
reference to a (non-member) function, so that different subclasses can
use different generator functions. But it seems Python is treating the
function as a member function because the reference to it is in class
Here's a simple case of what I'm trying (in the real code, fn is a
function that returns a database connection relevant to that subclass):
> def foo():
> print "foo called"
> class S(object):
> fn = foo
> def bar(cls):
> bar = classmethod(bar)
> def foo2():
> print "foo2 called"
> class D(S):
> fn = foo2
[I'm on python 2.3.4 so no @classmethod decorator! ]
When I run this:
> Traceback (most recent call last):
> File "t_o.py", line 19, in ?
> File "t_o.py", line 10, in bar
> TypeError: unbound method foo2() must be called with D instance as first argument (got nothing instead)
This shows it is trying to do what I expect (call foo2()) but somehow
the type is all wrong.
I've tried playing with staticmethod() but I can't quite get it all
More information about the Python-list