I have a python code that extracts info from database. The results are stored in a tuple within a list. I would like to store the tuple information in a class object. Since there are more than one result returned from query, I want to use List of class Object. I do not know how to assign value. Below is the snippet:
#Class
class StudentDetails():
def __init__(self, id, Name, Status):
self.id= id
self.Name= Name
self.Status= Status
def main():
results= LinkCursor.fetchall() #databse results
The result is of form list: [(1, 'XYZ', 'P'), (2, 'ABC', 'P'), (3, 'DEF', 'A'), (4, 'MNO', 'P')]
In Summary, I want to store result in different Class objects, Student1 =StudentDetails(1, 'XYZ', 'P') Student2 =StudentDetails(2, 'ABC', 'P')
You can just iterate your list of tuples while instantiating StudentDetails
:
l = [(1, 'XYZ', 'P'), (2, 'ABC', 'P'), (3, 'DEF', 'A'), (4, 'MNO', 'P')]
my_students = [StudentDetails(*tup) for tup in l]
my_students
# [<__main__.StudentDetails at 0x7fea5a8259b0>,
# <__main__.StudentDetails at 0x7fea5a825208>,
# <__main__.StudentDetails at 0x7fea5a825cf8>,
# <__main__.StudentDetails at 0x7fea5a825cc0>]
my_students[0].Name
# 'XYZ'
my_students[1].Name
# 'ABC
Or you can use dict
:
d = {"Student%s" %i : StudentDetails(*tup) for i, tup in enumerate(l)}
d['Student1'].Name
# 'XYZ'
I think this works with your question.
class StudentDetails():
def __init__(self, id=1, Name="manoj", Status="Active"):
self.id= id
self.LinkName= Name
self.LinkStatus= Status
li = [(1, 'XYZ', 'P'), (2, 'ABC', 'P'), (3, 'DEF', 'A'), (4, 'MNO', 'P')]
list_obj = []
for i in list:
student_details = StudentDetails()
student_details.id = i[0]
student_details.LinkName = i[1]
student_details.LinkStatus = i[2]
list_obj.append(student_details)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.