Home > Net >  How to add a user defined object to a class in Python
How to add a user defined object to a class in Python

Time:07-16

I have tried to create a program to store some datum of students. I want to create a function that ask the user to input the name and gpa of the student and create an object of that student. I have entered Amy as the name. But I am facing an error saying that the "Amy" is not defined.

class student:
    #Constructor
    def __init__(self, name, gpa):
        self.name = name
        self.gpa = gpa
    
    #Method
    def get_info(self):
        return self.name, self.gpa

def add_student():
    name = input("Please enter a student name: ")
    gpa = input("Please enter the gpa of {a}: ".format(a = name))
    print("{a} with gpa {b} is saved in the database.".format(a = name, b = gpa))
    name = student(name, gpa)

def print_info(name):
    c, d = name.get_info()
    print("Name: {a} GPA: {b}".format(a = c, b = d))

add_student()
print_info(Amy)

Please help! How can I get the user input and create an object with those info and get the ability to print the info with a function. Any help will be highly appreciated.

CodePudding user response:

I have found a solution that is creating a new variable every time the user enter a new student. I will declare it as global variable so that function outside the class can assess the object (Reference: [duplicate]How do you make a new variable while a program is running in python? [duplicate])

My New Code:

class student:
    #Constructor
    def __init__(self, name, gpa):
        self.name = name
        self.gpa = gpa
    
    #Method
    def get_info(self):
        return self.name, self.gpa

def add_student():
    user_input = input("Please enter a student name: ")
    gpa = input("Please enter the gpa of {a}: ".format(a = user_input))
    globals()[user_input] = student(user_input, gpa)
    print("{a} with gpa {b} is saved in the database.".format(a = user_input, b = gpa))

def print_info(name):
    c, d = name.get_info()
    print("Name: {a} GPA: {b}".format(a = c, b = d))

add_student()
print_info(Amy)

Please tell me if I am wrong.

  • Related