python - 在类对象中存储未绑定(bind)的 python 函数

标签 python function

我正在尝试在 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/

相关文章:

python - 在 pandas 数据框中添加具有相同列值的行

python - 如何将词干提取应用到字典中?

python - Pandas -Python : How do you write new lines in Pandas?

python - Django:没有 CSS 和正确文本的 html

iphone - ios - 创建函数

python - Python中的函数和C++中的函数有什么区别?

c - 为什么我们在 c 中声明后使用 clrscr() 函数?

python - 何时在 setup.py 中使用 pip 需求文件与 install_requires?

javascript - 文本输入大于2后使div可见

Powershell 中的函数 - 可以在字符串中调用它们吗?