0
import numpy as np

class test:
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

arr = []

for i in range(10):
    x = np.random.uniform(0, 5, 2)
    t = test(x[0], x[1])
    arr.append(t)

print(arr[:].num1)

This gives me the error 'list' object has no attribute num1.

If I instead use a for loop to cycle through the list, then it prints out just fine:

for i in range(len(arr)):
    print(arr[i].num1)

What gives?

mcqueen
  • 11
  • 2
    Because you just can't access the attribute of a list of objects like that. That's not how python works. You need to use a loop. – rdas Feb 11 '21 at 12:16
  • Btw `for i in range(len(...))` is an [anti-pattern](https://stackoverflow.com/questions/53358753/why-we-use-rangelen-in-for-loop-in-python). In many cases, including this one, `for element in arr` would be suitable and cleaner. Then you would just do `print(element.num1)`. – costaparas Feb 11 '21 at 12:17
  • your `arr` is only normal python list - not numpy array, nor pandas dataframe - and normal python list don't have method to get `num1` from all elements on list. You need `for`-loop or list comprehension like `[item.num1 for item in arr]` – furas Feb 11 '21 at 16:44

1 Answers1

0

Add the __repr__ method and then by using [array] you can obtain all the information of your class, you can see more here: https://www.geeksforgeeks.org/print-objects-of-a-class-in-python/

import numpy as np

class test:
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2
        
    def __repr__(self):  
        return "num1:% s num2:% s" % (self.num1, self.num2)
arr = []

for i in range(10):
    x = np.random.uniform(0, 5, 2)
    t = test(x[0], x[1])
    arr.append(t)

print([arr])
Joaquín
  • 350
  • 2
  • 12