[英]Passing function to class in Python
So I'm working on a class structure for a text-based menu. 因此,我正在为基于文本的菜单设计类结构。 I need to create the menus and set the actions before actually running the code.
在实际运行代码之前,我需要创建菜单并设置操作。 So to avoid the function being called to early, I have created a class called Run which takes the given function and runs it.
因此,为了避免过早调用该函数,我创建了一个名为Run的类,该类接受给定的函数并运行它。 My problem is that I don't know how I should handle the arguments for the function.
我的问题是我不知道该如何处理该函数的参数。 What I have so far, and which doesn't work is:
到目前为止,我无法使用的是:
class Run:
def __init__(self, func):
self.func = func
def execute(self):
print('Running')
self.func
def foo(*args):
print(*args)
baz = Run(foo('bar'))
baz.execute()
Just to be clear I first want the function to run when I run baz.execute()
为了清楚
baz.execute()
我首先希望函数在运行baz.execute()
时运行
You are calling the function before you pass it to Run
, so func
is actually the result of calling it ( None
, as it doesn't return anything). 您是在将函数传递给
Run
之前调用该函数的,所以func
实际上是调用它的结果( None
,因为它不返回任何内容)。 The minimal fix is: 最小修复是:
class Run:
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def execute(self):
print('Running')
self.func(*self.args, **self.kwargs) # call func here
baz = Run(foo, 'bar') # don't call func here
baz.execute()
However, you can just use functools.partial
to do this, removing the need to maintain your own class and tack .execute
onto the eventual call (which you could also eliminate by renaming execute
to __call__
: 但是,您可以只使用
functools.partial
来执行此操作,无需维护您自己的类并将.execute
到最终调用上(您也可以通过将execute
重命名为__call__
来消除这种情况:
>>> from functools import partial
>>> def foo(*args):
print(*args)
>>> baz = partial(foo, 'bar')
>>> baz
functools.partial(<function foo at 0x1059c4400>, 'bar')
>>> baz()
bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.