[Python] Create class instances with dictionary keys as instance name

Discussão em 'Python' iniciado por Stack, Junho 8, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dictionary with course names and some info on each course. I want to dynamically create Courses() instances for each of the 4 courses in the dictionary. But I want to be able to reference them by the actual course name such as math.limit. Is there a way to dynamically instantiate new instances of a class using the keys from a dictionary as the variable name? Or any other way? I created an instance named math manually and it works as it should, but if you have 500 courses it would be very tedious to do manually.

    class Courses:

    def __init__(self, course, course_id, limit):
    self.course = course
    self.course_id = course_id
    self.limit = limit

    def __str__(self):
    return f'Course: {self.course}, Course ID: {self.course_id}, Limit: {self.limit}'

    courses = {'English': {'course_id': 1000, 'limit': 30},
    'Math': {'course_id': 1001, 'limit': 20},
    'History': {'course_id': 1002, 'limit': 50},
    'Science': {'course_id': 1003, 'limit': 25},
    }

    math = Courses('Math', 1001, 20)
    print(math)

    Course: Math, Course ID: 1001, Limit: 20

    Continue reading...

Compartilhe esta Página