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