Python中ActionScript的 apply()/call() 方法的等价实现?
我正在为我的Django项目写一个很简单的函数,这个函数只在应用程序处于调试模式时显示一些页面。在AS3中,你可以通过一个方法的调用或应用方法,把一个方法的参数应用到另一个方法上。让我给你演示一下:
public function secureCall(...arguments):void {
if (SECURE == true) {
// reference the 'call' method below
call.apply(this, arguments);
} else {
throw new IllegalAccessError();
}
}
public function call(a:String, b:int, ...others):void {
// do something important
}
在Python中有没有办法做到这一点?我基本上想要做的是:
from django.views.generic.simple import direct_to_template
def dto_debug(...args):
if myapp.settings.DEBUG:
direct_to_tempate.apply(args)
else:
raise Http404
2 个回答
3
你可以使用动态参数。direct_to_template
这个函数的定义是:
def direct_to_template(request, template, extra_context=None, \
mimetype=None, **kwargs):
你可以这样调用它:
args = (request, template)
kwargs = {
'extra_content': { 'a': 'b' },
'mimetype': 'application/json',
'additional': 'another keyword argument'
}
direct_to_template(*args, **kwargs)
5
在定义一个函数的时候,你可以用这样的写法:
def takes_any_args(*args, **kwargs):
pass
args
会是一个包含位置参数的元组,kwargs
则是一个包含关键字参数的字典。
然后你可以用这些参数来调用另一个函数,像这样:
some_function(*args, **kwargs)
如果你不想传位置参数或者关键字参数,可以选择不写 *args
或 **kwargs
。当然,你也可以自己创建这个元组或字典,它们不一定要来自 def
语句。