2011-10-04 48 views
1

我正在寫一個非常簡單的函數,用於我的Django項目中,只有當應用程序處於調試模式時才顯示多個頁面。在AS3中,您可以使用該方法的調用或應用方法將方法參數應用於其他方法。讓我證明:Python的ActionScript等價於apply()/ call()方法嗎?

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 
+0

使用'function(* arguments)'notation – JBernardo

回答

5

當定義一個函數,你可以使用這個符號:

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

args將是一個位置參數元組, kwargs關鍵字參數字典

然後,您可以調用另一個函數,這些參數是這樣的:

some_function(*args, **kwargs) 

您可以省略的*args**kwargs的,如果你不希望傳遞位置或關鍵字參數,分別。你當然可以自己創建元組/字典,他們不必來自def聲明。

+1

太棒了,那就是我一直在尋找的東西。到目前爲止,我一直在Python中對'*'和'**'前綴變量的功能感到困惑。 –

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)