在Python中动态显示数组所有键的最佳方法

2024-04-29 03:11:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的新手,我想知道是否有更好的解决方案来动态显示对象下的所有属性(关键字、woe\u代码、时间戳)。你知道吗

原始代码:

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"

Tags: 对象代码infor属性modelsall解决方案
2条回答

您可以使用__dict__

for t in trends:
    for k, v in t.__dict__.items():
        if not k.startswith('__'):
            print k, v

您可以使用内置的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
"""

相关问题 更多 >