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.

Nemo
  • 1,124
  • 2
  • 16
  • 39
  • 1
    How _didn't_ https://stackoverflow.com/questions/51142320/how-to-instantiate-class-by-its-string-name-in-python-from-current-file solve your problem exactly? – deceze Apr 08 '23 at 07: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*? – juanpa.arrivillaga Apr 08 '23 at 07: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)` – Nemo Apr 08 '23 at 10:23
  • @deceze, because when I ran this code adapted from the link `factory(classname='Year1')`, I got an error `TypeError: Student.__init__() missing 1 required positional argument: 'age'`. Would you mind showing me what I did wrong with the adapted code? – Nemo Apr 08 '23 at 10:38
  • 1
    Where the duplicate does `cls()`, you’ll need to pass your argument as well, e.g. `cls(age)`. – deceze Apr 08 '23 at 11:41
  • Thanks @deceze. I modified the code according to your advice like this `def factory(classname, age): cls = global()[classname] return cls(age)` then ran `test = factory(classname='Year1', age=6)`. Unfortunately, `test` returned `Student()` instead of `Year1(6)`. Could you please help? – Nemo Apr 08 '23 at 11:58
  • How does that work? Where did you see “Student()” and how? That’s not something Python would output by default. – deceze Apr 08 '23 at 12:09
  • @deceze, I realised my mistake for not defining the name for Year1, hence `test` returned `Student()` instead of `Year1()`. Thanks for your tips. Would you mind provide a formal answer to my OP explaining the process proposed by the link https://stackoverflow.com/questions/51142320/how-to-instantiate-class-by-its-string-name-in-python-from-current-file, in particular explaining the function `global()` and why the function `factory()` managed to achieve my desired result like that otherwise all I did was copy and paste without learning anything! Thanks – Nemo Apr 08 '23 at 12:11
  • 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())`… – deceze Apr 08 '23 at 12:20

0 Answers0