[英]Import global List from another class in different python file
I am trying to read list values from another python file.我正在尝试从另一个 python 文件中读取列表值。 but I always get empty list但我总是得到空列表
A.py file .py 文件
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 B.py 文件
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. info 目前是 python 对象上的一个实例变量,它的更改应该发生在实例上。 To change add_items to update the variables in a static context.更改 add_items 以更新静态上下文中的变量。 change it to be a @classmethod.将其更改为@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.但看起来您可能想要创建类 A 的实例。
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.如果您确实想将它用作实例变量而不是静态变量,我会将 add_values 更改为__init__(self)
或构造函数,以便您可以这样做。
instance_of_a = A()
print(instance_of_a.info)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.