Question

I'm trying to learn how to correctly use classes in python, I'm fairly new to it but I cant get this class to return a string output of all the values. Ideally I'd like to be able to just str(packet) into a network socket.

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)

This code outputs nothing at all. repr() outputs <__main__.ARP instance at 0x2844ea8> which I guess is what it's meant to do?

Was it helpful?

Solution

You are missing an underscore in your __repr__ method name:

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

Python looks for __repr__, not __repr_.

Next, your __str__ method should refer to attributes on self, not to globals. Perhaps a str.join() call would be helpful here too:

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')])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top