如何基于googlesheetsapi正确打印对象列表属性?

2024-06-16 12:45:03 发布

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

我是Python新手,没有使用列表而不是数组的经验。我正在尝试特别打印包含在同一类型对象列表中的对象的一个属性。你知道吗

我看到了strrepr之间的一些差异,因为str没有打印我想要的内容。我读到这两个应该被定义,即使他们是完全相同的。当我现在输出时,我得到以下信息:

<bound method MacAuth.__str__ of XXXXXXXXXXXX>
<bound method MacAuth.__str__ of XXXXXXXXXXXX>
<bound method MacAuth.__str__ of XXXXXXXXXXXX>

其中XXXXXXXXXX实际显示的是正确的属性和我想要看到的内容。我不需要输出线的其余部分。你知道吗

此外,这些信息是从googlesheetsapi读取的单元格值(),所以我不确定这是否会引起问题。你知道吗

class MacAuth():

    def __init__(self, mac_address):
        self.mac_address = mac_address
        self.registerd_user = 'registerd_user'

    def __str__(self):
        return self.mac_address

    def __repr__(self):
        return self.mac_address

mac_list = list()
for i in range(start, end):
    mac = sheet.cell(i,2).value
    mac_list.append(MacAuth(mac))

for i in range(0,3):
    print(mac_list[i].__str__, sep='\n')

Tags: of对象self列表属性addressmacdef
2条回答

如果在打印时call方法,您将获得字符串值:

print(mac_list[i].__str__(), sep='\n')

看看str()docs。相关部分:

str(object) returns object.__str__(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object).

类似地,repr()调用__repr__()。你知道吗

docsprint()

All non-keyword arguments are converted to strings like str() does and written to the stream

因此print(obj)的行为类似于str(obj),只是它写入流而不是返回值。这意味着你的解决方案比你想象的要简单:

# you can iterate over the list directly
for mac_auth in mac_list:
    # sep='\n' is the default value, so you don't need to specify it 
    print(mac_auth)

作为旁注,你现在看到这个的原因是:

<bound method MacAuth.__str__ of XXXXXXXXXXXX>

因为方法MacAuth.__str__也是一个对象,定义了它自己的字符串表示,并且print将方法转换为字符串。你知道吗

绑定方法的表示包括对它们绑定到的对象的引用,在本例中是MacAuth对象。流程与此类似:

  1. print()尝试将绑定到MacAuth对象的方法__str__(它本身就是一个对象)转换为字符串
  2. __str__的字符串表示包括它绑定到的对象,类似于<bound method MacAuth.__str__ of [MacAuth obj]>
  3. 要打印[MacAuth obj]部分,将调用该对象的__str__,它根据需要返回mac_address属性

相关问题 更多 >