Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting tuples instead of ints when creating an instance of a class? [closed]

I'm working on a little project where I'd like to collect data from MODBUS slaves and put them in a database. I decided to do it in python, because it has some nice modules for handling both MODBUS and mysql. I am very much new to python and wanted to do some testing first, just to warm up and get some basic understanding of the language.

My idea is to have a class with its attributes being the same as columns in my database table, and then I can load stuff into an instance of this class, manipulate it if I need to, and insert the data into the database.

I have encountered a problem with the types of attributes, however. My class looks like this:

class Sensor:
def __init__(self, id, s_id, type, s_pin, off, loc, desc, desc_l):
    self.id = id,
    self.slave_id = s_id,
    self.type = type,
    self.slave_pin = s_pin,
    self.offset = off,
    self.sensor_location = loc,
    self.desc = desc,
    self.desc_long = desc_l

Now, I create an instance of the class:

Sens = Sensor(4, 1, "temp", 2, 0.0, "Jupiter", "Temp Sens 4_D1_P2", "Temperature Sensor on Jupiter LOL")

The problem is that, even though VS Code tells me 4, and 1, and 2 are ints, and the strings are strings and so on, when I call:

print(type(Sens.id))

I get the answer that it's a

<class 'tuple'>

Even though, clearly, it should be an int. Same for the "offset" which should be a float, or the strings.

HOWEVER, interestingly enough, the last attribute "desc_long" is in fact a string.

I've searched the web, and I'm pretty sure my init() function is correct, and I'm creating the instance properly as well. Can anyone explain to me why it's a tuple, and not an int (or a float)?

like image 830
occamzchainsaw Avatar asked Oct 15 '25 03:10

occamzchainsaw


2 Answers

In this case,

self.id = id,

creates a single element tuple. It might be more obvious if you add parenthesis

self.id = (id,)

Remove the commas to prevent them from being interpreted as tuples.

like image 188
Carcigenicate Avatar answered Oct 16 '25 16:10

Carcigenicate


To fix this, remove the commas from your init method's assignments to self as such:

class Sensor:
    def __init__(self, id, s_id, type, s_pin, off, loc, desc, desc_l):
        self.id = id
        self.slave_id = s_id
        self.type = type
        self.slave_pin = s_pin
        self.offset = off
        self.sensor_location = loc
        self.desc = desc
        self.desc_long = desc_l

If you have a declaration like the following, you get a tuple.

var = 3,
like image 34
eLymar Avatar answered Oct 16 '25 17:10

eLymar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!