zra*_*ram 0 python variables scope dart
例如,在 Python 中我们有一个非局部特征:
nonlocal 关键字用于处理嵌套函数内的变量,其中变量不应属于内部函数。使用关键字nonlocal 来声明该变量不是局部的。
nonlocal 语句声明,每当我们更改名称 var 的绑定时,绑定都会在已绑定 var 的第一帧中更改。回想一下,如果没有非本地语句,赋值语句将始终在当前环境的第一帧中绑定名称。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
Run Code Online (Sandbox Code Playgroud)
我无法使用的 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;
}
Run Code Online (Sandbox Code Playgroud)
当我nonlocal在这里输入时,它给了我错误。
对于上下文,这是我学习并尝试将 Python 代码转换为 Dart 的地方:
https://compositionprograms.com/pages/24-mutable-data.html#local-state
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |