Chris
Chris

Reputation: 337

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'. Then I want to be able to refer to the information in the form

output_data[0].Pressure

I've done similar things in visual basic. However with this code I get a list output_data = [Test_data], and then I get the error

'TypeError: 'Test_data' object does not support indexing'

any ideas to fix the problem, or alternative methods to achieve what I want

Upvotes: 0

Views: 96

Answers (1)

John Gordon
John Gordon

Reputation: 33335

Add a class-level attribute that keeps track of all the instances.

Inside __init__(), add self to that list.

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.

Upvotes: 2

Related Questions