keeping a ref to a non-member function in a class
Gregory Bond
gnb at itga.com.au
Tue Aug 16 03:57:39 EDT 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
scope....
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):
> cls.fn()
> bar = classmethod(bar)
>
> def foo2():
> print "foo2 called"
>
> class D(S):
> fn = foo2
>
> D.bar()
[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 ?
> D.bar()
> File "t_o.py", line 10, in bar
> cls.fn()
> 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
worked out...
More information about the Python-list
mailing list