python - 在 python 27 中,如何将带参数的方法传递给类的 __init__()?

标签 python class python-2.7 module parameter-passing

我正在尝试将一个参数传递给一个我想从类的实例调用的函数,但我不知道该怎么做。如果我不传递任何参数,我可以做得很好,但当我开始传递参数时,一切都在我面前爆炸了。

这是我想做的一个例子。

class foo:
    def __init__(self, use_function=None):
        self.use_function = use_function

    def call(self):
        self.use_function()

def bar(number):
    print 'number is ' + str(number)

myObj = foo( use_function=bar(15) )

myObj.call()

最佳答案

你不能传递参数,因为你的 __init__ 函数不接受参数,它只接受函数。如果您传递 bar(15),它会调用 bar before __init____init__ 接收 bar(15)返回值(在本例中为 None)。

如果你想让 __init__ 调用 bar(15),你可以做 foo( use_function=lambda: bar(15) )。这将传递给 __init__ 一个零参数函数,该函数在调用时将调用 bar(15)

关于python - 在 python 27 中,如何将带参数的方法传递给类的 __init__()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32600073/

相关文章:

Python 试图从文件中写入和读取类,但出现了可怕的错误

python - 使用 streamlink 将流作为单个帧处理

flash - AS3 模板(如 C++)

html - 为什么要使用 ID 选择器而不是类?

python - Python 的机器人框架关键字 : Error with unmatched string or IP. 如何解决此问题?

python - 如何在python中将md5 32字节哈希转换为相应的sha256

python - Linux 上的 cffi 包安装错误

c++ - 如何避免需要初始化初始化列表中的成员对象?

python - 删除音乐文件元数据标签

google-app-engine - ndb.StructuredProperty 不保存 key ?