开发者

Python equivalent of ActionScript's apply()/call() methods?

I'm writing a pretty simple function for use in my Django project to display a number of pages only if the application is in debug mode. In AS3, you can essentially apply a methods parameters to another methods using that method's call or apply method. Let me demonstrate:

public function secureCall(...arguments):void {
    if (SECURE == true) {
        // reference the 'call' method below
        call.apply(this, arguments);
    } else {
        throw new IllegalAccessError();
    }
}

public开发者_JS百科 function call(a:String, b:int, ...others):void {
    // do something important
} 

Is there a way to do this in Python? I essentially want to do the following:

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


When defining a function, you can use this notation:

def takes_any_args(*args, **kwargs):
    pass

args will be a tuple of positional arguments, kwargs a dict of keyword arguments

You can then call another function with these arguments like this:

some_function(*args, **kwargs)

You can omit either of the *args or **kwargs if you don't want to pass positional or keyword arguments, respectively. You can of course create the tuple/dict yourself, they don't have to come from a def statement.


You can use dynamic parameters alright. The function signature for direct_to_template is:

def direct_to_template(request, template, extra_context=None, \
                       mimetype=None, **kwargs):

You can call this like so:

args = (request, template)
kwargs = {
    'extra_content': { 'a': 'b' },
    'mimetype': 'application/json',
    'additional': 'another keyword argument'
}

direct_to_template(*args, **kwargs)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜