Hi, pretty new to Python, done some coding in C++. I’m trying to write a simple class that returns a value. My main code works (in the ‘else’ statement), so I’m trying to put in a check to stop it from crashing with an empty or too short string. My problem is the ‘if’ statement executes always. If I print the length of canID it shows ‘8’, but if I print the length of self.canID it shows ‘0’. I don’t understand what I’m doing wrong.
class GetAddress():
''' TAKES A HEX CAN_ID AND RETURNS A MODULE ADDRESS '''
def __init__(self, canID):
print(len(canID))
self.canID = canID
# check for 8 digits
if len(self.canID) < 8:
print(len(self.canID))
self.modAddr = hex(255)
else:
# trim to the desired digits
# xxxxNNNx
self.canID = canID[4:7]
# change the resulting hex value to binary value
self.bv = bin(int(self.canID, 16))[2:].zfill(12)
# discard the rightmost bit and take the
# remaining right six bits '[6:11]'
self.bv = int(self.bv[6:11],2)
# the resulting number is a string...
# convert it to int(base 2) then hex
self.modAddr = hex(int(self.bv))
def __str__(self):
# return the resulting hex value as string
return str(self.modAddr)
address = GetAddress("08f336f0")
address = GetAddress("")
print(address)
result:
8
0
0xff