针对现有Java API的Python API设计
我是python新手,我必须设计一个类似于现有Java API的python API(版本-2.7) Python版本-2.7 JavaAPI如下所示针对现有Java API的Python API设计,java,python,python-2.7,closures,Java,Python,Python 2.7,Closures,我是python新手,我必须设计一个类似于现有Java API的python API(版本-2.7) Python版本-2.7 JavaAPI如下所示 public interface Process<T> { Future<T> create(Client<T> client) //Other methods } public interface Client<T> extends Serializable { T execu
public interface Process<T> {
Future<T> create(Client<T> client)
//Other methods
}
public interface Client<T> extends Serializable {
T execute(ClientContext c)
//Other methods
}
public interface ClientContext {
File createFile(String path)
//Other methods
}
方法2
我可以使用闭包直接将上下文传递给Process类的create函数,以便消除客户端类吗
注意Process类的create方法将处理异步任务,这些任务可以使用python中的concurrent.futures包完成
我想知道这两种方法中哪一种是好的
也可以使用更好的方法。一般来说,我会使用闭包来创建函数模板,就像我想用不同的变量生成同一模板的许多函数一样 范例
def add(x):
def addto(y):
return x+y
return addto
addto5 = add(5)
print addto5(1)
#will print 6
在您的情况下,闭包看起来不是一个好的选择,因为在闭包中,您只能更改变量,但函数过程(模板)是常量,而在带有继承的普通类中,它将给您更多的自由感谢您的响应。您能告诉我如何将上下文直接传递给流程类的create函数吗?这很简单,只需创建客户机对象并将其直接传递给这样的流程create(client().execute(context))客户机是一个抽象类,我知道的唯一方法就是使用类似于此类型的类型方法(“ClientImpl”,(client,object){“execute”:lambda self,context:context}()。execute(None)这里的type方法从客户机动态创建子类并重写那里的execute函数。然后我用None调用它以确保代码正常工作
def add(x):
def addto(y):
return x+y
return addto
addto5 = add(5)
print addto5(1)
#will print 6