2014-10-10 45 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