Home > Back-end >  I need to access variables across files, what should I do?
I need to access variables across files, what should I do?

Time:10-05

How can I make MyClassB access the dict k in MyClassAC?

I have two files, the first file is MyClassB.py, the content is as follows:

class MyClassB:
    print('This is MyClassB!')

    @classmethod
    def run(cls):
        for _i in cls.codes:
            print(k[_i])  #  What code should I write here to access k defined in MyClassAC?

#If k is relatively large, will it affect performance if it is written in the class attribute?

The content of the main file MyClassAC.py is as follows:

from MyClassB import MyClassB


class MyClassA:
    codes = range(3)
    print('This is MyClassA!')


class MyClassC(MyClassB, MyClassA):
    print('This is MyClassC!')
    pass


k = {}
for i in MyClassC.codes:
    k[i] = MyClassC

MyClassC.run()

CodePudding user response:

You could pass k into the run() method:

class MyClassB:
    print('This is MyClassB!')

    @classmethod
    def run(cls, k):
        for _i in cls.codes:
            print(k[_i])

and the call can be modified like this:

k = {}
for i in MyClassC.codes:
    k[i] = MyClassC

MyClassC.run(k)
  • Related