I'm trying to do the following in python:
In a file called foo.py:
# simple function that does something:
def myFunction(a,b,c):
print "call to myFunction:",a,b,c
# class used to store some data:
class data:
fn = None
# assign function to the class for storage.
data.fn = myFunction
And then in a file called bar.py: import foo
d = foo.data
d.fn(1,2,3)
However, I get the following error:
TypeError: unbound method f() must be called with data instance as first argument (got int instance instead)
This is fair enough I suppose - python is treating d.myFunction as a class method. However, I want it to treat it as a normal function - so I can call it without having to add an unused 'self' parameter to the myFunction definition.
So the question is:
How can I store a function in a class object without the function becoming bound to that class?
data.fn = staticmethod(myFunction)
should do the trick.
What you can do is:
d = foo.data()
d.fn = myFunction
d.fn(1,2,3)
Which may not be exactly what you want, but does work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With