Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way I can make a list of class instances?

I wanted to make a list of class instances. I’m using Python 3.12.4.

I tried:

class MyClass:
    def __init__ (self,MyClassData):
        self.MyClassData = MyClassData
MyClassList = [""]
MyClassList.append(MyClass("hello"))
def ReadClassData () :
    for i in MyClassList:
        return MyClassList[i].MyClassData
print(ReadClassData())

and it returns:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Traceback (most recent call last):
  File "C:/Users/malac/OneDrive/Documents/Python/Tests/Instance In List.py", line 9, in <module>
    print(ReadClassData())
  File "C:/Users/malac/OneDrive/Documents/Python/Tests/Instance In List.py", line 8, in ReadClassData
    return MyClassList[i].MyClassData
TypeError: list indices must be integers or slices, not str

I’m confused on that last part. I thought [i] was an integer?

>Solution :

Here’s a walkthrough of what happens:

class MyClass:
    def __init__ (self,MyClassData):
        self.MyClassData = MyClassData

You defined the class MyClass. So far, so good

MyClassList = [""]
MyClassList.append(MyClass("hello"))

MyClassList is a list initiated with a single element (empty string ""), and is immediately appended with the object MyClass("hello"). MyClassList is now ["", MyClass("hello")]

def ReadClassData () :
    for i in MyClassList:
        return MyClassList[i].MyClassData
print(ReadClassData())

The for loop iterates through MyClassList, got its first element, i.e. "", and assign it to i, so i is now "". That’s why it shows an error because you’re trying to access an element of the list MyClassList with a str index

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading