【问题标题】:Python: Change class variable with method from another filePython:使用另一个文件中的方法更改类变量
【发布时间】:2018-05-15 09:50:30
【问题描述】:

我想用另一个文件中的方法更改主文件中的类字典。当我调用该方法时,它的行为就像它完成了它的工作一样,但是当再次从主文件调用字典时,它会丢失附加的条目。

主文件,testmain.py

import testside


class MainClass(object):
    objects = {'three': 'four'}


if __name__ == '__main__':

    testside.SideClass.add_to('one', 'two') # prints {'three': 'four', 'one': 'two'}
    print(MainClass.objects)                # prints {'three': 'four'}

侧文件,testside.py

import testmain


class SideClass(object):

    @staticmethod
    def add_to(name, thing):
        testmain.MainClass.objects[name] = thing
        print(testmain.MainClass.objects)

如何从文件外部更改类值?请注意,我不想创建MainClass() 的实例。

【问题讨论】:

  • 这个例子不应该工作,因为你正在创建一个循环导入
  • 谢谢,我很担心循环导入,但我还没有找到关于如何避免它们的好读物。你有什么要推荐的吗?

标签: python python-3.x class import


【解决方案1】:

SideClass 正在导入它自己的 MainClass 类副本。您需要传入要更改的副本(即使它不是实例!),因为 MainClass 已在其自己的文件中读取。

这有效: 主文件,testmain.py

import testside

class MainClass(object):
    objects = {'three': 'four'}


if __name__ == '__main__':
    testside.SideClass.add_to(MainClass, 'one', 'two') # prints {'three': 'four', 'one': 'two'}
    print(MainClass.objects)                # prints {'three': 'four', 'one': 'two'}

侧文件,testside.py

class SideClass(object):

    @staticmethod
    def add_to(cls, name, thing):
        cls.objects[name] = thing
        print(cls.objects)

作为奖励,您不再需要在 SideClass 中导入 MainClass,并且可以动态地将 SideClass 用于您想要的任何类。

我觉得不得不问,你为什么要这样做?这个问题有点X-Y问题的味道。

【讨论】:

  • 我需要用对象列表创建字典。我需要通过名称从任何地方(任何文件?)轻松访问它们,所以我认为最简单的方法是在程序的主文件中创建一个字典。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 2023-01-26
  • 2017-09-28
  • 2013-01-12
  • 2019-07-30
  • 1970-01-01
  • 2020-11-16
相关资源
最近更新 更多