Andrea Vitale
Andrea Vitale

Reputation: 25

How can I dynamically create an object of a class in python 3?

I'm trying (as a personal exercise for practicing with classes) to create a sort of school register. I have created the class Student but then I want that the user inserts the info for each student but I really can't fugured out how to do it (I would have to create a variable to create an object)... I searched online but I found ittle of nothing and what I find was stuff about 11 years ago and using python 2...

class Student(object):
    def __init__(self, name, surname, age, grade, address):
        self.name = name
        self.surname = surname
        self.age = age
        self.grade = grade
        self.address = address

number_of_students = input('How many students do you want to create? --> ')

for x in range(number_of_students):
    #create a student entering the infos
    pass

So. this is the class and a for loop just to see how to dynamically create objects (later I'd like to create a function to do it)

Upvotes: 0

Views: 362

Answers (1)

Nasir Hussain
Nasir Hussain

Reputation: 105

Get all required fields, create object, store objects somewhere i.e. in a list

class Student(object):
    def __init__(self, name, surname, age, grade, address):
        self.name = name
        self.surname = surname
        self.age = age
        self.grade = grade
        self.address = address

def create_student():
    name = input("Enter name")
    surname = input("Enter surname")
    age = input("Enter age")
    grade = input("Enter grade")
    address = input("Enter address")
    return Student(name, surname, age, grade, address)

number_of_students = input('How many students do you want to create? --> ')
students = []
for x in range(number_of_students):
    #create a student entering the infos
    students += [create_student()]

Upvotes: 1

Related Questions