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

How do i get my code to loop through all attributes of an object?

I just learned python and i’m trying to see what is possible.
When i made this testscript the code gave an error.

class test():
    list = {}
    value = 0
    def __init__(self, *args) -> None:
        y = 0
        self.value = test.value
        test.list[self.value] = []
        for x in args:
            self.x = y
            y += 1
            test.list[self.value].append(x)
        test.value +=1
        print (test.list[self.value])
        for i in test.list[self.value]: print (self.i)

a = test("a", "b", "c", "d")

This code should output:
["a", "b", "c", "d"]

0
1
2
3

But instead i get an error saying "AttributeError ‘test’ object has no attribute ‘i’".
How do i get the code to go trough all the attributes of a and output it’s value.

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

>Solution :

I guess the error occur here:

for i in test.list[self.value]: print (self.i)

should be:

for i in test.list[self.value]: print (i)

UPDATE

In this example you get both Numbers first and then the letters:

class test():
    def __init__(self, *args) -> None:
        my_list = []
        value = 0
        y = 0
        value = 0
        for x in args:
            my_list.append(x)
            print(y)
            y += 1
        print (my_list)
        for i in my_list: print (i)

a = test("a", "b", "c", "d")
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