我有个问题。你看,我想做的和这个Java代码一样:
new Runnable() {
//run() is a method that you need to
//implement when you create any
//new instance of Runnable
public void run() {
//Code goes here
}
}
Java让您实现抽象方法,比如Runnable。问题是,我试图在Python中复制相同的东西,在类的init方法中传递一个参数,然后将该方法作为变量存储在类中(自我评价法) 我在该类的代码中稍后的某个时候运行该方法。问题是,方法的所有参数都必须在创建类时传递,而不是在调用方法时传递,也就是我要传递参数的时候:
class AbstractExample():
def __init__(self, method):
method #Run method
def exampleMethod(arg1,arg2):
print str(arg1) + "," + str(arg2)
AbstractExample(exampleMethod(5,7))
输出是:“5,7”,如果我在创建类时没有传递参数,我会得到一个错误。我的问题是,有没有什么方法可以用另一种方法来编写上面的Java代码?你知道吗
首先,要运行
method
,应该使用method()
。你知道吗另外,在将它传递给
AbstractExample
之前执行exampleMethod
。你可以这样做:Python没有类似于Java的抽象类。可以将可调用项作为函数参数的值传递。你知道吗
在我看来,您想要的是存储一个callable及其参数,以便以后执行。以下是部分:
然后可以传递p和em变量作为函数参数。你知道吗
也许这就是你想要做的:
相关问题 更多 >
编程相关推荐