【问题标题】:Given an instance of a type object, how do you call the constructor of the class (equivalent of GetConstructor in other languages)给定一个类型对象的实例,如何调用该类的构造函数(相当于其他语言的GetConstructor)
【发布时间】:2019-10-25 04:08:36
【问题描述】:

看起来很简单,但是如果只给定一个类型,我不知道如何获取类构造函数。 为了清楚起见,我创建了一个代码 sn-p,将问题作为函数存根演示。

Google 没有提供任何有用的信息,也许我找不到合适的关键字来避免 SEO 将我推向流行的 Python 网站介绍。

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))

请随时致电我的 unpythonic 询问此问题;我知道问这个问题表明我应该为手头的问题寻求更健康的方法。

非常感谢任何帮助。

【问题讨论】:

    标签: python class reflection constructor


    【解决方案1】:

    由于type(Person) 是type,您可以使用类名作为替代。该类可以从globals 实例化,使用**-operator 将字典传递给构造函数。这是一个例子:

    def magic_thing_maker(the_type, ctor_args):
        return globals()[the_type](**ctor_args)
    
    some_type = Person.__name__
    the_person = magic_thing_maker(some_type, {'name':'Saul Goodman',
    'age':37})
    

    请参阅此question 了解更多信息。 要从导入的模块中实例化类,您可以使用getattr,请参阅此question。

    【讨论】:

      猜你喜欢
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多