0

I have 3 classes as such:

class Year1(Student):
    def action():
        ...

class Year2(Student):
    def action():
        ...

class Year3(Student):
    def action():
        ...

How can I instantiate those objects from a list of tuples of their string names and integer values like this :

ls = [('Year1', 10), ('Year2', 15), ('Year3', 25)]

to this:

years = [Year1(10), Year2(15), Year3(25)]

This question didn't help me solve the problem.

9
  • 1
    How didn't stackoverflow.com/questions/51142320/… solve your problem exactly? Commented Apr 8, 2023 at 7:19
  • Why do you have a list of such strings? If you really must use strings, create a dictionary mapping those strings to the class, then just use the class to instantiate the object. But the best solution is to avoid the strings in the first place. Again, why the strings? Commented Apr 8, 2023 at 7:43
  • @juanpa.arrivillaga It was a task where I was required to instantiate objects from a given list of tuples in the form of ('str', int) Commented Apr 8, 2023 at 10:23
  • 1
    Where the duplicate does cls(), you’ll need to pass your argument as well, e.g. cls(age). Commented Apr 8, 2023 at 11:41
  • 1
    All you really need is globals()[cls_name]. That gives you the class object from its name as a string. The rest is up to you and your specific class. Do you understand what this single expression does? If not, play around with print(globals()) Commented Apr 8, 2023 at 12:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.