0

I'm new to python and I've been trying new things. I made this class:

class Student(object):
    def __init__(self,school,gpa,age):
        self.school=school;
        self.gpa=gpa;
        self.age=age; 
    def stu_info(self):
        print("School: ",self.school)
        print("GPA:", self.gpa)
        print("Age:",self.age)

and then I typed this code to create objects of the class. The problem is taht I wish to use the input() function to enter the name of the object. Here is the code I wrote (which does not work).

School=input("What is your school's name? \n")
Gpa=input("What is GPA? \n")
Age=input("How old are you? \n")
StudentName=input("Name: ")
StudentName=Student(School,Gpa,Age)
print("Saved")

You can see that my problem is in these lines:

Name=input("Name: ")
Name=Student(School,Gpa,Age)

An object with the name (StudentName) is always created and I can get the information by using StudentName.stu_info().

Do you have any ideas on how I can use the value of StudentName as a name of an object?

thank you in advance

1 Answers1

0
name = input("Name: ")
locals()[name] = Student(School,Gpa,Age)

But don't do that. Instead use a dictionary:

students = {}
students[name] = Student(School,Gpa,Age)
Rich Tier
  • 9,021
  • 10
  • 48
  • 71
  • I used the first method and worked just fine for me.. why shouldn't I use it? And I reall didn't get the dictionary method.. – Mazen Alghamdi Nov 17 '18 at 02:08
  • Because it's a hack. `locals` is a mutable dictionary of available variable names. When you access `some_variable`, it's looked up from `locals`. You're polluting locals by putting all your students in there. Less polluting will be to use a dictionary – Rich Tier Nov 17 '18 at 12:47