如何更改引用不同类的不同python文件中变量的值?

2024-09-28 01:26:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个主python文件和一个不同python文件中的类。我试图从类中更改python文件中的一个变量。但是,我不知道如何在__init__函数之外执行此操作

班级:

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

主文件:

from Matrices import Matrices

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

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

这意味着要更改主文件中的otherControls变量,但它只在本地更改它。我无法访问__init__函数之外的原始otherControls变量。有人能帮忙吗


Tags: 文件函数selfrighttrueinitdefclass
1条回答
网友
1楼 · 发布于 2024-09-28 01:26:45

如果将矩阵对象保存为变量,例如

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

您可以如下方式访问otherControls属性:

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

相关问题 更多 >

    热门问题