今天遇到写代码想打印下实例的具体的值,索性写了个简单的递归
def getattrValue(obj,i):
print " "*i,type(obj)
for x in dir(obj):
if hasattr(obj,x) and "__" not in x:
if "method" not in str(getattr(obj,x)) and "object" in str(getattr(obj,x)) or "class" in str(getattr(obj,x)):
print " "*i,"attrName:",x," is object has attr:"
getattrValue(getattr(obj,x),i+1)
else:
if "method" in str(getattr(obj,x)):
pass
else:
print " "*i,"attrName:",x
print " "*i," value:",getattr(obj, x)
简单测试:
#test
class MyObject(object):
def __init__(self):
self.x = 9
self.j = MyObject2()
def power(self):
return self.x * self.x
class MyObject1(object):
def __init__(self):
self.uu = 122
self.y = MyObject()
self.x = 122
def power(self):
return self.x * self.x
class MyObject2(object):
def __init__(self):
self.k = 5
def power(self):
return self.x * self.x
if __name__ == '__main__':
obj = MyObject1()
getattrValue(obj,0)
结果如下: