例如,在 Python 中,我們有一個非本地特性:
nonlocal 關鍵字用于處理嵌套函式內的變數,其中變數不應屬于內部函式。使用關鍵字 nonlocal 來宣告該變數不是本地的。
nonlocal 陳述句宣告,每當我們更改名稱 var 的系結時,系結會在已系結 var 的第一幀中更改。回想一下,如果沒有 nonlocal 陳述句,賦值陳述句總是會在當前環境的第一幀中系結一個名稱。nonlocal 陳述句表示名稱出現在環境中的某個位置,而不是第一個(本地)幀或最后一個(全域)幀。
Dart中是否有類似的東西?
這是來自 Python 的代碼示例:
def make_withdraw(balance):
"""Return a withdraw function that draws down balance with each call."""
def withdraw(amount):
nonlocal balance # Declare the name "balance" nonlocal
if amount > balance:
return 'Insufficient funds'
balance = balance - amount # Re-bind the existing balance name
return balance
return withdraw
我無法使用的 Dart 的偽翻譯nonlocal:
makeWithdraw(balance) {
//Return a withdraw function that draws down balance with each call.
withdraw(amount) {
var nonlocal balance; //Declare the name "balance" nonlocal
if (amount > balance){return 'Insufficient funds';}
balance = balance - amount //rebind the existing balance name
return balance;}
return withdraw;
}
當我nonlocal在這里輸入時,它給了我錯誤。
對于背景關系,這是我學習并嘗試將 Python 代碼轉換為 Dart 的地方:
https://composingprograms.com/pages/24-mutable-data.html#local-state
uj5u.com熱心網友回復:
Dart 是一種具有顯式變數宣告的詞法范圍語言。與源自 C 語法的其他編程語言一樣,變數在它們被宣告的地方被限定。(Python 需要global和nonlocal關鍵字,因為 Python 不需要顯式變數宣告,并且沒有這些關鍵字會隱式宣告新的區域變數。)
如果你想要一個非區域變數,只需在區域范圍之外宣告它。例如:
int globalVariable = 0;
void foo(int variableLocalToFoo) {
int anotherVariableLocalToFoo = 42;
void bar(int variableLocalToBar) {
int anotherVariableLocalToBar = variableLocalToFoo variableLocalToBar;
}
if (true) {
int variableLocalToBlock = 9;
}
}
class SomeClass {
int memberVariable = 0;
}
uj5u.com熱心網友回復:
makeWithdraw(balance) {
//Return a withdraw function that draws down balance with each call.
withdraw(amount) {
balance;
if (amount > balance) {
return 'Insufficient funds';
}
balance = balance - amount;
print(balance);
return balance;
}
return withdraw;
}
nonlocalTest() {
var wd = makeWithdraw(20);
wd(5);
wd(1);
wd(5);
}
好吧,即使沒有非區域變數,這個程式似乎在飛鏢中也能正常作業!似乎這種非區域賦值模式是具有高階函式和詞法范圍的編程語言的一般特征......!所以在 dart 中不需要 nonlocal,但是如果沒有 nonlocal 關鍵字,相同的程式在 python 中將無法運行!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/511300.html
標籤:Python镖变量范围
