18

我正在尝试在 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 的文件中: import foo

d = foo.data
d.fn(1,2,3)

但是,我收到以下错误:

TypeError:必须以数据实例作为第一个参数调用未绑定的方法 f()(改为获取 int 实例)

我想这很公平 - python 将 d.myFunction 视为类方法。但是,我希望它把它当作一个普通函数来对待——所以我可以调用它而不必在 myFunction 定义中添加一个未使用的“self”参数。

所以问题是:

如何在不绑定到该类的情况下将函数存储在类对象中?

4

3 回答 3

27
data.fn = staticmethod(myFunction)

应该做的伎俩。

于 2008-11-29T12:28:33.927 回答
1

你可以做的是:

d = foo.data()
d.fn = myFunction

d.fn(1,2,3)

这可能不是您想要的,但确实有效。

于 2008-11-29T13:38:20.557 回答
0

感谢安德烈的回答——太简单了!

For those of you who care, perhaps I should have included the entire context of the problem. Here it is anyway:

In my application, users are able to write plugins in python. They must define a function with a well-defined parameter list, but I didn't want to impose any naming conventions on them.

So, as long as users write a function with the correct number of parameters and types, all they have to do is something like this (remember, this is the plugin code):

# this is my custom code - all plugins are called with a modified sys.path, so this
# imports some magic python code that defines the functions used below.
from specialPluginHelperModule import *

# define the function that does all the work in this plugin:
def mySpecialFn(paramA, paramB, paramC):
    # do some work here with the parameters above:
    pass

# set the above function:
setPluginFunction(mySpecialFn)

The call to setPluginFunction takes the function object and sets it in a hidden class object (along with other plugin-configuration related stuff, this example has been simplified somewhat). When the main application wants to run the function, I use the runpy module to run the plugin code, and then extract the class object mentioned above - this gives me the configuration data and the plugin function so I can run it cleanly (without polluting my namespace).

This entire process is repeated multiple times for different plugins over the same input, and seems to work very well for me.

于 2008-11-30T10:21:24.167 回答