[英]List of Class Objects in Python
class Test_data(object):
def __init__(self):
# nothing in here as of yet
self.Time = 0.0
self.Pressure = 0.0
self.Temperature = 0.0
self.Flow = 0.0
This script creates the instance of the class 该脚本创建类的实例
import Test_data
output_data = []
dp = Test_data()
dp.add_data(matrix_out,line)
output_data.append(dp)
dp = []
I'm trying to create a list 'output_data' which is a list of the instances of the class 'Test_data'. 我正在尝试创建一个列表'output_data',它是类'Test_data'的实例的列表。 Then I want to be able to refer to the information in the form
然后,我希望能够参考表格中的信息
output_data[0].Pressure output_data [0]。压力
I've done similar things in visual basic. 我在Visual Basic中做过类似的事情。 However with this code I get a list output_data = [Test_data], and then I get the error
但是,使用此代码,我得到一个列表output_data = [Test_data],然后出现错误
'TypeError: 'Test_data' object does not support indexing' 'TypeError:'Test_data'对象不支持索引'
any ideas to fix the problem, or alternative methods to achieve what I want 解决问题的任何想法,或实现我想要的替代方法
Add a class-level attribute that keeps track of all the instances. 添加一个跟踪所有实例的类级属性。
Inside __init__()
, add self
to that list. 在
__init__()
内部,将self
添加到该列表中。
class Test_data(object):
instances = []
def __init__(self):
self.Time = 0.0
self.Pressure = 0.0
self.Temperature = 0.0
self.Flow = 0.0
Test_data.instances.append(self)
Then you can access Test_data.instances
for the list. 然后,您可以访问该列表的
Test_data.instances
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.