我正在尝试在 python 中执行以下操作:
在名为 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
然后在一个名为 bar.py 的文件中: 导入 foo
d = foo.data
d.fn(1,2,3)
但是,我收到以下错误:
TypeError: unbound method f() must be called with data instance as first argument (got int instance instead)
我想这很公平 - python 将 d.myFunction 视为类方法。但是,我希望它把它当作一个普通函数 - 这样我就可以调用它而不必将未使用的“self”参数添加到 myFunction 定义中。
那么问题是:
如何将函数存储在类对象中,而函数不会绑定(bind)到该类?
最佳答案
data.fn = staticmethod(myFunction)
应该可以解决问题。
关于python - 在类对象中存储未绑定(bind)的 python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/327483/