在Python中动态显示数组所有键的最佳方法
我是Python的新手,我想知道是否有更好的解决方案可以动态显示对象下的所有属性(关键字、woe_代码、时间戳) 原始代码:在Python中动态显示数组所有键的最佳方法,python,Python,我是Python的新手,我想知道是否有更好的解决方案可以动态显示对象下的所有属性(关键字、woe_代码、时间戳) 原始代码: trends = models.Trends.query.all() for t in trends: print t.keyword, t.woe_id, t.woe_code, t.timestamp #I know this is wrong, hardcoding the attributes. 新代码: trends = models.Trends.
trends = models.Trends.query.all()
for t in trends:
print t.keyword, t.woe_id, t.woe_code, t.timestamp #I know this is wrong, hardcoding the attributes.
新代码:
trends = models.Trends.query.all()
for t in trends:
for k, v in vars(t).iteritems():
print k+"KEY"
print v+"Value"
您可以使用内置的dir函数来获取对象属性的列表。像这样的
class T:
g = 1
t = 0
b = 2
t = T()
for attribute in dir(t):
print "attribute %s has value %s" % (attribute,getattr(t,attribute))
"""
--- outputs ---
attribute __doc__ has value None
attribute __module__ has value __main__
attribute b has value 2
attribute g has value 1
attribute t has value 0
"""
您可以使用
\uuuu dict\uuuu
:
for t in trends:
for k, v in t.__dict__.items():
if not k.startswith('__'):
print k, v
在这种情况下,“动态”是什么?只需打印字典的键和值?