将函数保存在元组中而不执行
我有一个如下所示的元组:
self.tagnames = (('string', self.do_anything()),)
如果一个字符串与另一个字符串匹配,它应该执行特定的函数。 但是,当我初始化 self.tagnames 时,它似乎已经执行了该函数。
如何在启动时不执行该函数的情况下解决我的问题?
I have a tuple like the following:
self.tagnames = (('string', self.do_anything()),)
It should execute a specific function if a string matches to another.
However, when I initialize self.tagnames
, it seems to execute the function already.
How can I fix my issue without executing the function on startup?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
()
是一个函数调用。如果您想将调用推迟到稍后,只需包含不带括号的函数引用,如下所示。The
()
is a function call. If you want to defer the call until later, and just include the function reference without the parens like so.您可以通过使用带参数列表的括号来调用函数:
len
是一个函数,len(s)
在参数s
上调用该函数。只需使用函数的名称即可获得该函数。去掉括号内的参数列表,您将不再调用该函数。You invoke a function by using parens with an argument list:
len
is a function,len(s)
is invoking that function on the arguments
. Simply using the function's name gets you the function. Leave off the parenthesized argument list, and you are no longer invoking the function.您应该删除括号:
显然
self.do_anything()
立即调用该方法,而不是self.do_anything
返回 Python 中所谓的“绑定方法”,即它是一个可调用对象,您可以仅向其传递参数(如果有),这将导致调用特定实例上的方法。You should just remove the parenthesis:
Clearly
self.do_anything()
calls the method immediately, insteadself.do_anything
returns what in Python is called a "bound method", i.e. it's a callable object to which you can pass just the parameters (if any) and that will result in calling the method on the specific instance.