Quoting a Python function in order to apply it later
Given an object Foo, which has a set of methods Bar, Baz, Quux, and Close.
I want to wrap calls into Foo as follows
def 开发者_如何学JAVAwrapper(method_symbol, *args):
object = Foo()
apply(object.method_symbol, args)
object.Close()
So later on, I can call wrapper(Bar, MySweetArgs)
and have wrapper correctly dispatch.
Obviously in Lisp this would be simple, simply QUOTE method_symbol
and away you go.
The goal is to properly allocate/deallocate resources in a text-efficient fashion. I would prefer not wrap all of Foo with a SafeFoo class.
If you want to call the method by its name, the wrapper
function could look like this:
def wrapper(method_symbol, *args):
obj = Foo()
getattr(obj, method_symbol)(*args)
obj.Close()
wrapper('Bar', 1, 2, 3)
You could also use the method directly, instead of its name:
def wrapper(method, *args):
obj = Foo()
method(obj, *args)
obj.Close()
wrapper(Foo.Bar, 1, 2, 3)
If method_symbol is the string name then:
Foo.__dict__[method_symbol](*args)
would probably do it.
精彩评论