2014-10-10 32 views
1

我无法弄清楚这一点,并花了相当多的时间在这里查看问题和答案,但似乎没有什么比较合适的。从数据库查询创建类实例 - Python

我有一个类定义为传感器创建一个实例,持有各种属性和功能。

在数据库中,我已定义连接的传感器。现在,如果有三个传感器,我不得不这么像这样...

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

你想要左侧是什么?如果它是Sensor_Id,您可以使用像sensorObjs [n [0]] – user3885927 2014-10-10 23:40:14

+0

这样的字典为什么不将它们存储在列表中? 'the_sensors = [传感器中n为[ClassName(n [0])]' – jacg 2014-10-10 23:46:49

+0

左侧我想成为从数据库派生的实例名称。数据库中的Sensor1将创建一个名为sensor1 = SensorClass(),sensor2 = SensorClass()等的新实例。 – 2014-10-10 23:58:16

回答

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)的诱惑,因为这会影响内建。

+0

工作正常!而且我从来没有想过要自己解决这个问题。谢谢你的帮助! – 2014-10-11 01:10:55

+0

@PhillipMurphy出于好奇,你选择了哪个版本? – jacg 2014-10-11 01:15:35

+0

我在这篇文章中使用了版本1。一旦你看到它是如何完成的,这是有道理的,但是哇 - 如何能够让人自己想出一个呢?再次感谢! – 2014-10-11 02:20:51