将未绑定的Python函数存储在类对象中 [英] storing unbound python functions in a class object

查看:129
本文介绍了将未绑定的Python函数存储在类对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在一个名为foo.py的文件中:

 #执行某些操作的简单函数:
def myFunction(a,b,c):
printcall to myFunction:,a,b,c

#用于存储某些数据的类:
类数据:
fn =无

#将函数分配给类进行存储。
data.fn = myFunction

然后在一个名为bar.py的文件中:
import foo

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

但是,我得到以下错误:


TypeError:必须使用数据实例作为第一个参数调用非绑定方法f()(而不是使用int实例)

我认为这很公平 - python将d.myFunction作为一个类方法处理。然而,我希望它把它当作一个正常的函数 - 所以我可以调用它而不必为myFunction定义添加一个未使用的'self'参数。



问题是:



如何将函数存储在类对象中,而不会将函数绑定到该类?

解决方案

  data.fn = staticmethod(myFunction)

应该这样做。


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.

这篇关于将未绑定的Python函数存储在类对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆