You're close. You want CRC to be a regular function1:
def CRC(bytearray_in):
'''Calculates a Cyclical Redundancy Checksum (CRC16).'''
crc = 0xFFFF
for work_byte in bytearray_in:
crc ^= work_byte
n = 0
while n in range(8):
if (crc & 0x0001):
crc >>= 1
crc ^= 0xA001
else:
crc >>= 1
n += 1
return crc
which you call from your subclass's init:
class EZTcomm(bytearray):
def __init__(self, *args, **kwargs):
bytearray.__init__(self, *args, **kwargs)
self.check = CRC(self)
inside __init__
, self is the instance of your subclass that you're creating. It's a bytearray, so it should work with CRC assuming CRC works at all. Of course, you can get more complicated here and use super
to do the calling of the base class's __init__
method:
class EZTcomm(bytearray):
def __init__(self, *args, **kwargs):
super(EZTcomm, self).__init__(*args, **kwargs)
# super().__init__(*args, **kwargs) # python3.x only.
self.check = CRC(self)
super
has the advantage that it makes things work nicely with multiple inheritance, but in general, I advise people to really know what they're doing before they start messing with it. There are a number of best practices that you should follow to get the most out of it. See: http://rhettinger.wordpress.com/2011/05/26/super-considered-super/ for some details.
1Your while loop would be better as a for
loop: for n in range(8):...
.
If you do that, you drop the n = 0
and n += 1
lines.