无法从Python类返回字符串

0 投票
1 回答
741 浏览
提问于 2025-04-18 06:07

我正在学习如何在Python中正确使用类,我对这方面还比较陌生,但我无法让这个类返回所有值的字符串输出。理想情况下,我希望能够直接将str(packet)发送到网络套接字。

class ARP():
    dst_addr = ''
    src_addr = ''
    type = '\x08\x06'
    payload = '\x00\x01\x08\x00\x06\x04\x00'
    arptype = '\x01'
    src_mac_addr = ''
    src_ip_addr = ''
    dst_mac_addr = ''
    dst_ip_addr = ''

    def __repr_(self):
        return 'ARP'
    def __str__(self):
        return dst_addr + src_addr + type + payload + arptype \
            + src_mac_addr + src_ip_addr + dst_mac_addr + dst_ip_addr


p = ARP()
p.dst_addr = router_mac 
p.src_addr = random_mac()
p.arptype = '\x02'
p.src_mac_addr = local_mac
p.src_ip_addr = ip_s2n(target_ip)
p.dst_mac_addr = router_mac
p.dst_ip_addr = ip_s2n(router_ip)

print 'PACKET: ', str(p)
return str(p)

这段代码什么都没有输出。repr()的输出是<__main__.ARP instance at 0x2844ea8>,我想这就是它应该输出的内容吧?

1 个回答

3

你的 __repr__ 方法名字里缺少了一个下划线:

def __repr_(self):
# ---------^

Python 是在找 __repr__,而不是 __repr_

接下来,你的 __str__ 方法应该引用 self 上的属性,而不是全局变量。也许在这里使用 str.join() 会很有帮助:

def __str__(self):
    return ''.join([getattr(self, attr) for attr in (
        'dst_addr', 'src_addr', 'type', 'payload', 'arptype', 'src_mac_addr',
        'src_ip_addr', 'dst_mac_addr', 'dst_ip_addr')])

撰写回答