Python 对象类型转换为元组类型
给对象添加一个 __iter__
函数:
file:[src/pojos.py]
class Cover:
def __init__(self, temp, accel_x, accel_y, accel_z, cover_status):
self.temp = temp
self.accel_x = accel_x
self.accel_y = accel_y
self.accel_z = accel_z
self.cover_status = cover_status
self.date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
# 通过定义 __iter__() 方法将其转换为元组或其他可迭代对象。
def __iter__(self):
yield self.temp
yield self.accel_x
yield self.accel_y
yield self.accel_z
yield self.cover_status
yield self.date
比如,在插入数据库的时候,把对象转换为元组类型,通过 tuple
函数转换:
file:[src/mysql_utils.py]
def insert_cover(data: pojos.Cover):
sql = "insert into covers (temp, accel_x, accel_y, accel_z, cover_status, date) values(%s, %s, %s, %s, %s, %s, %s, %s)"
exeSql(sql, tuple(data))