【问题标题】:How to change value of variable from different python file referenced different class?如何从引用不同类的不同python文件中更改变量的值?
【发布时间】:2020-02-07 05:25:24
【问题描述】:

我有一个主要的 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 变量。有人可以帮忙吗?

【问题讨论】:

  • 局部变量othercontrols != 类属性self.othercontrols

标签: python python-3.x class import scope


【解决方案1】:

如果您将矩阵对象保存到变量中,例如

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多