简体   繁体   中英

How to change value of variable from different python file referenced different class?

I have a main python file and a class in a different python file. I have tried to change a variable in the python file from the class. However, I don't know how to do this outside of the __init__ function.

The class:

class Matrices:
    currentMenuItem = 0
    dataForMatrix = {}

    def __init__(self, memory, matricesFrame, tempBoolsControl, otherControls):
        self.memory = memory
        self.matricesFrame = matricesFrame
        self.tempBoolsControl = tempBoolsControl
        self.otherControls = otherControls

    def createNewMatrix(self):
        self.otherControls["right"] = False

The main file:

from Matrices import Matrices

otherControls = {"right": True, "left": True}

Matrices(memory, matricesFrame, tempBoolsControl, otherControls).createNewMatrix()

This is meant to change the otherControls variable in the main file, but it only changes it locally. I can't access the original otherControls variable outside of the __init__ function. Can anyone help?

If you save the Matrices object to a variable, eg

mat = Matrices(memory, matricesFrame, tempBoolsControl, otherControls).createNewMatrix()

you can access the otherControls attribute like this:

mat.otherControls = {'right':True, 'left':False}
# or if you want only one of the keys
mat.otherControls['right'] = False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM