Change global variables from inside class method

后端 未结 2 541
面向向阳花
面向向阳花 2021-01-19 19:14

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,

2条回答
  •  [愿得一人]
    2021-01-19 19:42

    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)
    

提交回复
热议问题