从类内部方法更改全局变量 [英] Change global variables from inside class method
问题描述
当我尝试执行以下代码时,first_list会被修改,而第二个列表则不会发生任何变化.有没有一种方法可以将外部列表替换为全新的列表,或者只能从内部类方法中调用列表方法?我尝试在分配操作之前添加global关键字,但是会产生语法错误.
When I try to execute the code below, the first_list gets modified while no changes occur to the second one. Is there a way to replace an outside list with a brand new list, or calling list methods is the only thing I'm allowed to do from inside class methods? I tried adding global keyword before the assignment operation, but it produces a syntax error.
first_list = []
second_list = []
class MyClass:
def change_values(self):
first_list.append('cat')
second_list = ['cat']
test = MyClass()
test.change_values()
print(first_list)
print(second_list)
推荐答案
第一:拥有具有可变状态的全局变量几乎是从不.您应该将模块级变量用作常量或单例.如果要更改变量的值,则应将其作为参数传递给函数,然后从函数返回新值.
First: It's almost NEVER a good idea to have global variables with mutable state. You should use module level variables just as constants or singletons. If you want to change a value of a variable you should pass it as a parameter to a function and then return a new value from a function.
说您的问题的答案将是:
Said that the answer to your question would be either:
first_list = []
second_list = []
class MyClass:
def change_values(self):
first_list.append('cat')
second_list[:] = ['cat']
test = MyClass()
test.change_values()
print(first_list)
print(second_list)
或:
first_list = []
second_list = []
class MyClass:
def change_values(self):
first_list.append('cat')
global second_list
second_list = ['cat']
test = MyClass()
test.change_values()
print(first_list)
print(second_list)
这篇关于从类内部方法更改全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!