簡體   English   中英

通過數據庫查詢創建類實例-Python

[英]Create Class Instances from Database Query - 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是定義每個傳感器的數據庫表中的行數。

這讓我感到困惑-預先感謝!

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 )的誘惑,因為那樣會掩蓋內置函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM