【问题标题】:Accessing a list in a Class Object, Python访问类对象中的列表,Python
【发布时间】:2018-05-09 14:15:21
【问题描述】:

想了解如何从 python 中的返回对象中提取数据“桶”。 statuses 是一个存储桶,其中包含要显示的数据列表。我尝试了几种不同的方法,除了对象引用之外似乎什么都不能显示。基本上,在这个“桶”或数据列表中显示此类数据的最佳方式是什么。 ":type: list[ObjectedCreatedName]"

fetch = client.fetch('2Oe3UKM_Nt_NG1UG');
print(fetch.statuses)
print(type(fetch.statuses))

Output:
[<ObjectCreatedName object at 0x03CC07F0>]
<class 'list'>

class ObjectCreatedName(object):
     def __init__(self):
        self.code = None
        self.status = None
        self.count = None

【问题讨论】:

  • 它是列表所以使用[] 就像fetch.statuses[0].code 一样
  • 你应该给你的ObjectCreatedName 类一个__repr__ 和/或一个__str__ 方法。

标签: python python-3.x class object arraylist


【解决方案1】:

你可以:

def print_sequence(sequence):
    seq_type = sequence.__class__.__name__
    elem_type = sequence[0].__class__.__name__ if len(sequence) > 0 else ''
    print('{}[{}]'.format(seq_type, elem_type))

例如:

fetch = client.fetch('2Oe3UKM_Nt_NG1UG');
print_sequence(fetch.statuses)
# list[ObjectCreatedName]

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多