Home > Net >  Python - Problem returning True/False to class properties from class method
Python - Problem returning True/False to class properties from class method

Time:10-26

I have a class as below which within the __init__ method I am trying to assign a True/False value to a class property using a class method.

class Sensor:

    def __init__(self, json_data):
        self.sensor_eui = json_data['end_device_ids']['dev_eui']
        self.reading1 = json_data['uplink_message']['decoded_payload']['temperature']
        self.reading2 = json_data['uplink_message']['decoded_payload']['humidity']
        self.tolerance_exceeded = self.tolerance_check

   def tolerance_check(self):
        sql = f"SELECT DefaultLowerLimit, DefaultUpperLimit FROM [dbo].[IoT_Sensors] WHERE 
              DeviceID = '{self.sensor_eui}'"
        results = exec_sql(sql)

        if (self.reading1 > int(results[0])) and (self.reading1 < int(results[1])):
            return False
        return True

The issue is, when trying to troubleshoot this and logging the objects to the console, instead of returning True or False as the assigned value of 'tolerance_exceeded' it returns the method and object:

logging.info(f'Tolerance Exceeded: {sensor.tolerance_exceeded}')

logs in the console as below:

[2022-10-26T12:08:08.025Z] Tolerance Exceeded: <bound method Sensor.tolerance_check of <__app__.IoT_Data-Handler.classes.Sensor object at 0x000001C834D45BE0>>

So what is going on here? I have not been coding long, but when I have done something similar in the past (assigning a string value from an API), it worked fine. This is for an Azure Function, but I cannot see how that would impact what I am trying to achieve.

Any help would be appreciated.

CodePudding user response:

The issue in your code is that instead of calling the function you assign it. In order to call the function you have to add the parenthesis.

class Sensor:

    def __init__(self, json_data):
        self.sensor_eui = json_data['end_device_ids']['dev_eui']
        self.reading1 = json_data['uplink_message']['decoded_payload']['temperature']
        self.reading2 = json_data['uplink_message']['decoded_payload']['humidity']
        # Calling tolerance_check and assigning return value to tolerance_exceeded
        self.tolerance_exceeded = self.tolerance_check()
  • Related