Change global variables from inside class method

混江龙づ霸主 提交于 2019-12-01 18:45:38

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)

or:

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)

Use the global keyword inside the function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!