为什么 vars(type(, (object,), input_dict)()) 不返回其变量?



为了将dict转换为class,我编写了如下代码,它运行良好。

output_class = type('', (object,), input_dict)()

但是,创建的类不会通过下面的代码返回其属性!

print(vars(output_class))
>> {}

我使用下面的代码解决了这个问题,但我仍然感到困惑。

class Struct(object):
def __init__(self, **entries):
self.__dict__.update(entries)
output_class = Struct(**input_dict)
print(vars(output_class))
>> {'key': 'value'}

如果您能解释为什么前者不返回其属性,我将不胜感激。

这是因为在第一种情况下(调用类型(类的对象具有空__dict__并且您的input_dict内容存储在类变量中。type()的第三个参数定义了类(不是对象(变量或方法(它们由调用而不是__init____new__定义(。

简单地说,第一个和第二个代码片段是不一样的。

所以

output_class = type('', (object,), input_dict)()

有这样的等效内容:

class Struct(object):
def __new__(cls, **entries):
cls = super().__new__()
for k,v in **entries:
setattr(cls, k, v)
return obj
output_class = Struct()

如果你想要这样的东西:

class Struct(object):
def __init__(self, **entries):
self.__dict__.update(entries)
output_class = Struct(**input_dict)

你应该定义init((。它可能看起来像:

output_class = type('', (object,), 
{'__init__': lambda self, inp_d: self.__dict__.update(inp_d)})(input_dict)

如果我的解释不够清楚,我想这里的例子可以提供帮助:https://docs.python.org/3/library/functions.html#type 请注意:a 不在方法__init__(),因此它在类 X 的所有对象之间共享。

最新更新