If statement executes always

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

I think you are misinterpreting the output.

Your example calls the function twice. The first time with an 8 character address. It prints the length of canID (8) and then the if fails, so it executes the else block.

The second time it’s called with an empty string. It prints the length of canID(0) and does enter the if block. There it prints the length of self.canID (also 0).

Finally it prints address (the last return from the function) and that is 0xff.

So my output does not match what you’ve shown. I get two lines of 0.

8 # line 7 from GetAddress("08f336f0")
0 # line 7 from GetAddress("")
0 # line 12 from GetAddress("")
0xff # line 43

OMG, I’m an idiot! I see what is going on…, thank you for pointing it out.