简体   繁体   中英

Import global List from another class in different python file

I am trying to read list values from another python file. but I always get empty list

A.py file

import time
class A(): 
   info = []
   def add_values(self):
       x = 10
       while True:
          for i in range(x):
            self.info.append(i)
          i = x
          x = x + 10
          time.sleep(3)
          if len(info)> 1000:
            return
          print self.info
    def getinfo():
        return self.info

B.py file

from A import A
Class B()

  def useinfo():
      print A.getinfo()  

info is currently an instance variable on the python object, and changes to it should occur on the instance. To change add_items to update the variables in a static context. change it to be a @classmethod.

class A(): 
   info = []

   @classmethod
   def add_values(cls):
       x = 10
       while True:
          for i in range(x):
            cls.info.append(i)
          i = x
          x = x + 10
          time.sleep(3)
          if len(info)> 1000:
            return
          print(cls.info)

But it does look like you might want to create an instance of class A instead.

instance_of_a = A()
instance_of_a.add_values()

print(instance_of_a.info)

If you do want to use it as an instance variable instead of a static variable, I would change add_values to __init__(self) or the constructor so that way when you can just do this.

instance_of_a = A()
print(instance_of_a.info)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM