类'Test‘包含函数’test_变量‘。函数'update_d‘和'update_a’在'test_variables()‘中声明。变量'index‘在'test_variables’列表中初始化为0,1,2在'test_variables‘'update_d’和'update_a‘更新’索引‘中初始化并打印出来。我可以在不使用全局属性的情况下访问列表A的元素,但是为了访问'index‘,我在'update_d’和'update_a‘中声明了’全局索引‘。为什么我不能访问没有全局的变量索引,但是可以访问一个列表?
index=0
class Test():
def test_variables():
def update_d():
global index
index=index+1+A[0]
print(index)
def update_a():
global index
index=index+1+A[1]
print(index)
index=0
A=[1,2]
update_d()
update_a()
test_variables()发布于 2019-05-02 16:41:09
在Python中,只有在写入变量时才需要global关键字。在test_variable()中,您已经定义了一个名为index的新变量,尽管您的目的似乎是要写入在该作用域之外定义的变量。
当从变量名读取时,Python从最内部的作用域开始,如果找不到名称,则继续查找包含的作用域。
当您写入变量名时,Python只在本地查找,并在找不到其中一个名称时创建一个新变量。global关键字告诉Python,本地作用域应该在赋值时全局引用该名称。
因此,全局变量作为常量工作得最好,您需要更改的变量应该作为参数传递给函数并返回新值。
发布于 2019-05-02 16:34:17
列表A (除了update_a和update_b)是在Test中定义的,而index则不是。
发布于 2019-05-02 16:42:50
使用类是不正确的。
代码:
class Test:
A = (1, 2)
def __init__(self, index):
self.index = index
def update_d(self):
self.index += 1 + self.A[0]
print(self.index)
def update_a(self):
self.index += 1 + self.A[1]
print(self.index)
def test_variables(self):
self.update_d()
self.update_a()
idx = 0
tst = Test(idx)
tst.test_variables()提供的代码与您的代码相同,但使用正确的类。
https://stackoverflow.com/questions/55956714
复制相似问题