0

我多次調用外部庫的方法在我的課是這樣的:如何在Python中調用外部方法時解開元組?

class MyClass: 

    const_a = "a" 
    const_b = True 
    const_c = 1 

    def push(self, pushee): 
     with ExternalLibrary.open(self.const_a, self.const_b, self.const_c) as el: 
      el.push(pushee) 

    def pop(self): 
     with ExternalLibrary.open(self.const_a, self.const_b, self.const_c) as el: 
      return el.pop() 

with語句線纏着我,因爲他們需要每一次傳遞的常量作爲參數傳遞。我想將參數存儲在一個預定義的數據結構中,如元組,並將其傳遞給外部庫。

回答

3

你可以這樣做:

args = (const_a, const_b, const_c) 
ExternalLibrary.open(*args) 

*語法解壓可迭代(元組,列表等)插入一個函數調用參數的方式。還有一個**語法拆包字典到關鍵字參數:

kwargs = {'foo': 1, 'bar': 2} 
func(**kwargs) # same as func(foo=1, bar=2) 

您也可以在同一個電話同時使用,像func(*args, **kwargs)

+0

這是正確的。 Python文檔將其描述爲[解包參數列表](http://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists)。 – Bengt

相關問題