Python:使用另一个文件中的方法更改类变量

时间:2017-12-01 10:00:13

标签: python python-3.x class import

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

主文件 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()的实例。

1 个答案:

答案 0 :(得分:0)

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问题。