Python类实例化时属性为何为元组而非预期类型?
Hey there! I see exactly what's going on here—you've got a tiny syntax quirk causing those unexpected tuple types. Let's break this down:
The Root Cause
In your __init__ method, you added a trailing comma to every attribute assignment except the last one. In Python, when you end an assignment with a comma (without wrapping the value in parentheses), Python automatically treats that value as a single-element tuple instead of the raw data type you intended.
For example:
# This creates a tuple, not an int a = 4, print(type(a)) # Output: <class 'tuple'>
Since only your final desc_long = desc_l line doesn't have a trailing comma, it's the only one getting assigned the correct string type. All the previous attributes are being stored as single-element tuples.
The Fix
Simply remove those trailing commas from each assignment in your __init__ method. Here's the corrected code (I also renamed one parameter to avoid a keyword conflict):
class Sensor: def __init__(self, id, s_id, sensor_type, s_pin, off, loc, desc, desc_l): self.id = id self.slave_id = s_id self.type = sensor_type # Renamed 'type' to avoid clashing with Python's built-in keyword self.slave_pin = s_pin self.offset = off self.sensor_location = loc self.desc = desc self.desc_long = desc_l
Quick Best Practice Tip
type is a built-in Python keyword/function, so using it as a variable name can lead to confusing bugs down the line. Renaming it to something like sensor_type keeps your code clean and avoids conflicts.
Test It Out
After making this change, when you instantiate your Sensor class and check type(Sens.id), you'll get <class 'int'> as expected. All other attributes will now match their intended data types too.
内容的提问来源于stack exchange,提问作者occamzchainsaw

