我有以下代码:
mock_reporter_obj = type('DbUserObjMock', (object,), {
'uuid': 'test_uuid',
'username': 'test_username',
})()
test = mock_reporter_obj.__dict__
我希望测试得到以下结果
{
'uuid': 'test_uuid',
'username': 'test_username',
}
但是我得到的是空字典。
有人知道问题出在哪里吗,我如何获得在匿名函数上调用__dict__
的预期属性?
答案 0 :(得分:2)
uuid
和username
只是类属性,因此它们不属于实例属性字典(obj.__dict__
),但不属于类字典(cls.__dict__
):
mock_reporter_obj = type('DbUserObjMock', (object,), {
'uuid': 'test_uuid',
'username': 'test_username',
})
obj = mock_reporter_obj()
print(mock_reporter_obj.__dict__)
{'uuid': 'test_uuid', 'username': 'test_username', '__module__': '__main__', '__dict__': <attribute '__dict__' of 'DbUserObjMock' objects>, '__weakref__': <attribute '__weakref__' of 'DbUserObjMock' objects>, '__doc__': None}
如果您像往常一样声明类,也会发生同样的情况:
class A:
a = 9
a = A()
print(A.__dict__)
print(a.__dict__)
{'__module__': '__main__', 'a': 9, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
{}