Finding a Specific Class's Instance in a List

A. Keyton Weissinger keyton at weissinger.org
Wed Nov 28 04:08:41 CET 2001


Howdy Gang.

I have a list of several objects of various classes. I would like to most
quickly find the first instance of a given class and am still new to Python.
Is this the fastest way:

class Class1:
    def __init__(self, pName):
        self.wvName = pName

class Class2:
    def __init__(self, pName):
        self.wvName = pName

class Class3:
    def __init__(self, pName):
        self.wvName = pName

class Class4:
    def __init__(self, pName):
        self.wvName = pName

if __name__ == "__main__":
    myList = []
    myClass1A = Class1("Class1A")
    myClass1B = Class1("Class1B")
    myClass2 = Class2("Class2")
    myClass3 = Class3("Class3")
    myClass4 = Class4("Class4")

    myList.append(myClass1A)
    myList.append(myClass1B)
    myList.append(myClass2)
    myList.append(myClass3)
    myList.append(myClass4)

    print "My List:", myList
    i=0
    for obj in myList:
        if obj.__class__ == Class2:
            print "Found it at", i
        i += 1


Thank you in advance...

Keyton





More information about the Python-list mailing list