Python匿名实例调用__dict__返回空字典问题求助
问题原因分析
你遇到的问题核心在于:你通过type()创建类时,把uuid和username定义成了类属性,而非实例属性。
当你用type('DbUserObjMock', (object,), {'uuid': 'test_uuid', 'username': 'test_username'})创建类时,这些属性是绑定在类本身的,而不是绑定在实例上。实例化后,你访问mock_reporter_obj.uuid其实是在读取类的属性,但实例自己的__dict__(存储实例独有属性的字典)里并没有这些键值对,所以返回空字典。
解决办法
下面提供两种可靠的方式,让你能通过__dict__获取到预期的属性:
方式一:给动态类添加__init__方法初始化实例属性
通过在类定义中加入__init__方法,在实例化时把属性绑定到实例自身:
# 先定义初始化方法 def init_instance(self): self.uuid = 'test_uuid' self.username = 'test_username' # 创建动态类并实例化 mock_reporter_obj = type('DbUserObjMock', (object,), {'__init__': init_instance})() # 此时获取__dict__就能得到预期结果 test = mock_reporter_obj.__dict__ print(test) # 输出: {'uuid': 'test_uuid', 'username': 'test_username'}
方式二:实例化后手动给实例添加属性
如果你不需要复用这个动态类,也可以先创建空类,实例化后再给实例绑定属性:
# 创建空的动态类 mock_reporter_cls = type('DbUserObjMock', (object,), {}) # 实例化 mock_reporter_obj = mock_reporter_cls() # 给实例添加属性 mock_reporter_obj.uuid = 'test_uuid' mock_reporter_obj.username = 'test_username' # 读取__dict__ test = mock_reporter_obj.__dict__ print(test) # 输出: {'uuid': 'test_uuid', 'username': 'test_username'}
额外小技巧:用vars()替代直接访问__dict__
虽然不是必须,但Python中可以用内置函数vars()来获取实例的属性字典,效果和直接访问__dict__完全一致,写法更简洁:
test = vars(mock_reporter_obj)
内容的提问来源于stack exchange,提问作者lony
相关产品推荐
相关产品推荐

