jeudi 24 octobre 2019

Given an instance of a type object, how do you call the constructor of the class (equivalent of GetConstructor in other languages)

It seems simple, but I can't figure out how to get a class constructor if given only a type. For clarity I created a code snippet demonstrating the problem as a function stub.

Google is not turning up anything useful, maybe I can't find the right keywords to avoid the SEO driving me to popular intro to python sites.

from typing import NamedTuple

class Person(NamedTuple):
    name: str
    age: int

def magic_thing_maker(the_type, ctor_args):
    pass # I am stuck with what to do here

some_type = type(Person)
the_person = magic_thing_maker(some_type, {'name':'Saul Goodman', 
'age':37})

assert (the_person == Person('Saul Goodman', 37))

Feel free to call my unpythonic for asking this; I get that asking this question indicates I should seek healthier approaches to the problem at hand.

Any help much appreciated.





Aucun commentaire:

Enregistrer un commentaire