抽象方法,如J

2024-10-03 06:32:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题。你看,我想做的和这个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代码?你知道吗


Tags: 方法run代码younew参数initdef
2条回答

首先,要运行method,应该使用method()。你知道吗

另外,在将它传递给AbstractExample之前执行exampleMethod。你可以这样做:

class AbstractExample():

    def __init__(self, method):
        method() #Run method

def exampleMethod(arg1,arg2):
    print str(arg1) + "," + str(arg2)

AbstractExample(lambda: exampleMethod(5,7))

Python没有类似于Java的抽象类。可以将可调用项作为函数参数的值传递。你知道吗

class AbstractExample():

    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

    def call_now_with_my_parameters(self, callable):
        callable(self.arg2, self.arg2)

def example_function(arg1,arg2):
    print("{},{}".format(arg1, arg2))

ae = AbstractExample(5, 7)
ae.call_now_with_my_parameters(example_function)

在我看来,您想要的是存储一个callable及其参数,以便以后执行。以下是部分:

from functools import partial
p = partial(print, 'aef','qwe')
p()
em = partial(exampleMethod, 5, 6)
em()

然后可以传递pem变量作为函数参数。你知道吗

也许这就是你想要做的:

from functools import partial


class AbstractExample():

    def __init__(self, callable):
        callable() # call it now

def example_function(arg1,arg2):
    print("{},{}".format(arg1, arg2))

call_this_later = partial(example_function)
// you can pass call_this_later as parameter
ae = AbstractExample(call_this_later(5, 7))

相关问题 更多 >