为什么此功能未重置x
?
我的代码如下:
def reset():
x=0
x = 22
reset()
print(x)
预期结果x = 0
,实际结果x = 22
答案 0 :(得分:0)
您需要将x设为global
:
def reset():
global x
x = 0
答案 1 :(得分:0)
您需要了解有关Python范围的更多信息。对名称的赋值始终进入最内部的范围。global语句可用于指示特定变量位于全局范围内,应在该范围内反弹。非局部语句表示特定变量位于封闭范围内,应在该范围内反弹。
List<ComboBox> allCmbx = new List<ComboBox>();
List<string> allItems = new List<string> { "1", "2", "3", "4", "5" };
public MainWindow()
{
InitializeComponent();
ComboBox comboBox = new ComboBox();
comboBox.ItemsSource = allItems;
comboBox.DropDownClosed += ComboBox_DropDownClosed;
stackPanel.Children.Add(comboBox);
allCmbx.Add(comboBox);
}
private void ComboBox_DropDownClosed(object sender, EventArgs e)
{
ComboBox mainComboBox = (ComboBox)sender;
mainComboBox.DropDownClosed -= ComboBox_DropDownClosed;
ComboBox comboBox = new ComboBox();
allItems.Remove(mainComboBox.SelectedItem.ToString());
comboBox.ItemsSource = allItems;
comboBox.DropDownClosed += ComboBox_DropDownClosed;
stackPanel.Children.Add(comboBox);
allCmbx.Add(comboBox);
}
输出:
def scope_test():
def reset_local():
x = "local"
def reset_nonlocal():
nonlocal x
x = "nonlocal"
def do_global():
global x
x = "global"
x = "origin"
reset_local()
print("After local assignment:", x)
reset_nonlocal()
print("After nonlocal assignment:", x)
reset_global()
print("After global assignment:", x)
scope_test()
print("In global scope:", x)
请注意,本地分配(默认设置)如何不会更改scope_test的x绑定。非本地分配更改了scope_test的x绑定,而全局分配更改了模块级绑定。
您还可以看到在全局分配之前x之前没有绑定。
您可以查阅Python教程以获取更多信息:https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces。 希望或多或少地帮助您