I want to make an array (using the built-in array module), to create an array made up of classes. All the objects in the array will be the same class, but I want to be able to append new classes on the end and read the values.
Thanks in advance.

Recommended Answers

All 6 Replies

You are better off using a list of class instances.
Python arrays, like C arrays are meant to hold only very limited basic types.

OK cheers Vega :)
I'll have to look 'em up 'cos I'm not very good with lists.

Python lists are much simpler to use than arrays. Here is a small example of a list of instances ...

# explore Python class instances
# create a list of class instances and process them

class Person(object):
    def __init__(self, name=None, job=None):
        self.name = name
        self.job = job
        
    def __str__(self):
        """
        if used with the instance of the class, this overloads
        regular function str() and hence print() where str() is used
        """
        return "%s is a %s" % (self.name, self.job)


# a name:job sample dictionary
person_dict = {
"Mia Serts": "bicyclist",
"Adolph Koors": "master-brewer",
"Don B. Sanosi": "teacher",
"Zucker Zahn": "dentist"}

# convert the person dictionary to a list of class instances
person_list = []
for name, job in person_dict.items():
    person_list.append(Person(name, job))

# process the list of instances
# sort the person_list in place by name (actually first name) ...
import operator
person_list.sort(key=operator.attrgetter("name"))

# show all the persons
for instance in person_list:
    print(instance)

print('-'*30)

# search for a person by first name
search = "Don"
for instance in person_list:
    if search in instance.name:
        print(instance)

print('-'*30)

# search for a person by job
search = "dentist"
for instance in person_list:
    if search in instance.job:
        print("looked for a %s and found %s" % (search, instance.name))

""" result >>>
Adolph Koors is a master-brewer
Don B. Sanosi is a teacher
Mia Serts is a bicyclist
Zucker Zahn is a dentist
------------------------------
Don B. Sanosi is a teacher
------------------------------
looked for a dentist and found Zucker Zahn
"""

Aaah thanks again Vega :) You some kinda super hero or somethin'? ;)

Yes!:)

Thanks I've got it working now.
Looks like you've solved the case again, Vega!
;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.