Simas Paškauskas
Simas Paškauskas

Reputation: 623

Converting an array of arrays into a class array in Python

I know that this is a basic question, but I'm new to Python and seem to be unable to find an answer for. Let's say I have a user in my database with fields: name, surname, age. I make a user class in Python:

class User:
    def __init__(self, array):
        self.name = array[0]
        self.surname = array[1]
        self.age = array[2]

When I access my DB and call for the users I get the array of arrays.

def get_users():
    cursor.execute("SELECT * FROM `users`")
    return cursor.fetchall() #returns [[],[],[],[]...]

What is the simplest way to make every array in the arrays into the class?

[User, User,User,User,...]

(so when I'm iterating threw the elements in for loop, I could call user.name instead of user[0]) Is there a function for that or should I just go threw every single one element in the array and convert it into a class object?

Upvotes: 0

Views: 915

Answers (1)

deadshot
deadshot

Reputation: 9051

Using map()

res =  [ ["James","Jenkinson", 23],["Alice","Madison",25]]
x = list(map(User, res))
for user in x:
    print(user.name,user.surname, user.age)

Output:

James Jenkinson 23
Alice Madison 25

Upvotes: 2

Related Questions