0

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?

4
  • can you post the user data you are getting from db Commented May 9, 2020 at 7:46
  • It would be somewhere in the lines of: [ ["James","Jenkinson", 23],["Alice","Madison",25]....] Commented May 9, 2020 at 7:48
  • you iterate the resuts. for each element you create a new user u = User( elem ) and add that to a list that then contains all your users. Maybe use a dict instead to add them to, if you got a unique identifier so you can look them up fast later. Commented May 9, 2020 at 7:49
  • Maybe have a look into orm mappers that do the task for you automagically: fullstackpython.com/object-relational-mappers-orms.html Commented May 9, 2020 at 7:50

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.