Array of Objects

Working with arrays of objects is very similar to working with arrays of records, but using constructors and methods instead of accessing record attributes directly.

Creating Arrays of Records

Method 1a (SQA Arrays)

This creates an array of None types as placeholders.

These are then replaced by objects using the init constructor method.

#
computers = [None for c in range(20)]
#
computers[0] = Computer('AHS1913013','Desktop','Windows Vista')
#

Method 1b (SQA Arrays)

This requires a constructor method that uses default values for attributes, and setter methods to give each attribute a value.

#
computers = [Computer() for c in range(20)]
#
computers[0].setID = 'AHS1913013'
computers[0].setType = 'Desktop'
computers[0].setOS = 'Windows Vista'
#

Method 2 (Python Lists)

Use constructor methods to add new objects to a list:

#
computers = []
#
computers.append(Computer('AHS1913013','Desktop','Windows Vista'))
computers.append(Phone('XYZ1234567','Android 8','EE'))

Traversing an Array of Objects

Do not access, or alter, attribute values directly. User getter and setter methods instead.

Method 1 – by index

for c in range(len(computers)):
    str = computers[c].getID()
    str += " is a "
    str += computers[c].getType()
    print(str)

Method 2 – by object

for computer in computers:
    str = computer.getID()
    str += " is a "
    str += computer.getType()
    print(str)