keeping a ref to a non-member function in a class
Peter Otten
__peter__ at web.de
Tue Aug 16 05:35:45 EDT 2005
Gregory Bond wrote:
> 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've tried playing with staticmethod() but I can't quite get it all
> worked out...
You are on the right track with staticmethod, but you have to apply it to
fn:
>>> def foo(): print "first foo"
...
>>> def foo2(): print "second foo"
...
>>> class S(object):
... fn = staticmethod(foo)
... def bar(cls):
... cls.fn()
... bar = classmethod(bar)
...
>>> class D(S):
... fn = staticmethod(foo2)
...
>>> S.bar()
first foo
>>> D.bar()
second foo
In its current form, the bar() method is not necessary:
>>> S.fn()
first foo
>>> D.fn()
second foo
Peter
More information about the Python-list
mailing list