Home > Back-end >  How do i get my code to loop through all attributes of an object?
How do i get my code to loop through all attributes of an object?

Time:02-28

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.

CodePudding user response:

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")
  • Related