转 python中把class转dictionary 报错

In python, how do I cast a class object to a dict

用dict(w)报错
Traceback (most recent call last):
File “test.py”, line 23, in
print(a._dict )
AttributeError: ‘A’ object has no attribute ‘_dict

c:\zd_zxjtzq\RC_trashes\temp>python test.py
Traceback (most recent call last):
File “test.py”, line 23, in
print( dict(a) )
TypeError: ‘A’ object is not iterable

解决办法:
1,def 中直接把class内容设置成 dict

2,
Option 2: Override ’ iter‘.

Like this, for example:

def iter(self):
yield ‘a’, self.a
yield ‘b’, self.b
yield ‘c’, self.c
Now you can just do:

dict(my_object)
This works because the dict() constructor accepts an iterable of (key, value) pairs to construct a dictionary. However, note that accessing values using the get item obj[“a”] syntax will not work, and keyword argument unpacking won’t work. For those, you’d need to implement the mapping protocol.

3,
Option 3: Implement the mapping protocol.

The mapping protocol requires that you provide (at minimum) two methods together: keys() and getitem.

class MyKwargUnpackable:
def keys(self):
return list(“abc”)
def getitem(self, key):
return dict(zip(“abc”, “one two three”.split()))[key]
Now you can do things like:

m=MyKwargUnpackable()
m[“a”]
‘one’
dict(**m)
{‘a’: ‘one’, ‘b’: ‘two’, ‘c’: ‘three’}

dict(w)
{‘a’: ‘one’, ‘c’: ‘three’, ‘b’: ‘two’}

source: https://stackoverflow.com/questions/35282222/in-python-how-do-i-cast-a-class-object-to-a-dict

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值