在 对象(object)这是作为数据组织形式时,可以很方便获取对象的属性,进而很方便实现 obj 和 dict 的转换...
举例:
对象的属性:
>>> class A():
... pass
...
>>> a = A()
>>> a
<__main__.A instance at 0x108bb3368>
>>> a.name = 'jia'
>>> a.age = 20
>>> dir(a)
['__doc__', '__module__', 'age', 'name']
>>> a.__dict__
{'age': 20, 'name': 'jia'}
>>> a.name
'jia'
>>> a.age
20
#!/usr/bin/env python
# coding=utf-8
#class转dict,以_开头的属性不要
def props(obj):
pr = {}
for name in dir(obj):
value = getattr(obj, name)
if callable(value):
print 'value is callable, name:%s, value: %s' % (name, value)
if not name.startswith('__') and not callable(value) and not name.startswith('_'):
pr[name] = value
return pr
# 将class转dict,以_开头的也要
def props_with_(obj):
pr = {}
for name in dir(obj):
value = getattr(obj, name)
if not name.startswith('__') and not callable(value):
pr[name] = value
return pr
# dict转obj,先初始化一个obj
def dict2obj(obj,dict):
obj.__dict__.update(dict)
return obj
class A():
pass
a = A()
a.name = 'jia'
a.age = 20
print props(a)
print props_with_(a)
b = {'age': 21, 'name': 'b'}
obj = dict2obj(A(), b)
print dir(obj)
def test():
print 'come into test'
a.test = test
print props(a)
output:
{'age': 20, 'name': 'jia'}
{'age': 20, 'name': 'jia'}
['__doc__', '__module__', 'age', 'name']
value is callable, name:test, value: <function test at 0x101301ed8>
{'age': 20, 'name': 'jia'}
python object与dict互相转换
https://www.cnblogs.com/zipon/p/8078763.html
简介:
这里介绍了获取对象属性的实现。
网友评论