我无法解决这个问题,而且花了很多时间在这里挖掘问题和答案,但似乎没有什么比这更合适。
我有一个定义的类,它为传感器创建一个实例,包含各种属性和函数。
在数据库中,我定义了连接的传感器。现在,如果有三个传感器,我必须这样......
sensor1 = Sensor(1)
sensor2 = Sensor(2)
sensor3 = Sensor(3)
我想做的是遍历数据库,返回所有已定义的传感器(足够简单),然后根据该列表创建类的实例。
我无法弄清楚如何获取sqlite查询的结果并使其成为类实例的名称......
con = sqlite.connect('temp.db')
with connection:
cur = connection.cursor()
cur.exectute('SELECT Sensor_Id FROM Sensors')
sensors = cur.fetchall()
# I want to do something like this. The right side of the statement is correct, but how
# can I make the left side of the assignment be dynamic based on SQL result?
for n in sensors:
***sensorN*** = ClassName(n[0])
基本上我需要创建一个类的X个实例,其中X是数据库表中定义每个传感器的行数。
这个让我感到困惑 - 提前谢谢!
答案 0 :(得分:0)
con = sqlite.connect('temp.db')
with connection:
cur = connection.cursor()
cur.exectute('SELECT Sensor_Id FROM Sensors')
sensor_ids = cur.fetchall()
# I would recommend this approach
sensor = { sid : Sensor(sid) for sid in sensor_ids }
# Which allows you to access them as
sensor['Main-hall-3'], sensor['Flap-track-fairing-7'] # etc.
# If the sensor ids are integers, you might prefer
sensor = { int(sid) : Sensor(sid) for sid in sensor_ids }
# Which allows you to access them as
sensor[3], sensor[7] # etc
# If you know that the ids are going to be CONSECUTIVE INTEGERS
# STARTING AT 0, then you could do
sensor = [ Sensor(sid) for sid in sensor_ids ]
# Which allows you to access them as
sensor[0], sensor[1] # etc
# Now, if you *really* insist on having the sensors bound to names,
# then you could try
import sys
current_module = sys.modules[__name__]
for sid in sensor_ids:
setattr(current_module, 'sensor{}'.format(sid), Sensor(sid))
# Which would allow you to access them as
sensor1, sensor2 # etc
最后一个选项的一个缺点是,在引用传感器的全局变量和不传感器的全局变量之间没有明确的界限。基于字典的方法(前两个建议)和基于列表的方法(第三个建议)使得访问所有传感器变得容易,除了传感器之外什么都没有。例如(在前三种情况下),很容易在所有传感器上循环;在最后一种情况下,它更加棘手。
奖励:请注意,我已经抵制了使用名称id
(而不是sid
)的诱惑,因为这会掩盖内置内容。