I'm using Python 2.7 (can't upgrade). I'm trying to store a function in my class, which can be overridden with a different function in the ctor. The function is a normal, static function (not a member or class method) so I don't want to pass the class or object as the first parameter when I invoke it. For some reason, Python always passes the object as the first parameter. How do I avoid this?
Example:
def fn(*args):
print str(args)
class MyClass(object):
myfn = fn
def __init__(self, myfn=None):
if myfn is not None:
self.myfn = myfn
def run(self, arg):
self.myfn(arg)
o = MyClass()
o.run("foo")
When I run this, I get the object as the first argument to fn
:
$ python /tmp/testfn.py
(<__main__.MyClass object at 0x7f7fff8dc090>, 'foo')
If I don't add the class member myfn
and instead only assign the value in the ctor then it works as expected:
def __init__(self, myfn=None):
self.myfn = fn if myfn is None else myfn
$ python /tmp/testfn.py
('foo',)
But, I don't want to do this because I want to be able to reset the function for the entire class so all future objects automatically get the new function, in addition to being able to reset it for an individual object.
I don't understand why the class member value behaves differently. Is there any way I can convince python that this function is a static function (don't pass the object as the first argument)?