我正在開發另一個數據採集項目,該項目已經變成面向對象的編程問題。在我的代碼底部的「main」中,我創建了Object DAQInput的兩個實例。當我寫這個時,我認爲我的方法.getData會引用特定實例的taskHandle,但它不會。當我運行時,代碼使用第一個句柄執行兩次getData任務,很顯然,我不太瞭解Python中的面向對象編程。對不起,如果沒有PyDAQmx和附加的National Instruments主板,這些代碼將無法運行。Python中的兩個類實例沒有不同
from PyDAQmx import *
import numpy
class DAQInput:
# Declare variables passed by reference
taskHandle = TaskHandle()
read = int32()
data = numpy.zeros((10000,),dtype=numpy.float64)
sumi = [0,0,0,0,0,0,0,0,0,0]
def __init__(self, num_data, num_chan, channel, high, low):
""" This is init function that opens the channel"""
#Get the passed variables
self.num_data = num_data
self.channel = channel
self.high = high
self.low = low
self.num_chan = num_chan
# Create a task and configure a channel
DAQmxCreateTask(b"",byref(self.taskHandle))
DAQmxCreateAIThrmcplChan(self.taskHandle, self.channel, b"",
self.low, self.high,
DAQmx_Val_DegC,
DAQmx_Val_J_Type_TC,
DAQmx_Val_BuiltIn, 0, None)
# Start the task
DAQmxStartTask(self.taskHandle)
def getData(self):
""" This function gets the data from the board and calculates the average"""
print(self.taskHandle)
DAQmxReadAnalogF64(self.taskHandle, self.num_data, 10,
DAQmx_Val_GroupByChannel, self.data, 10000,
byref(self.read), None)
# Calculate the average of the values in data (could be several channels)
i = self.read.value
for j in range(self.num_chan):
self.sumi[j] = numpy.sum(self.data[j*i:(j+1)*i])/self.read.value
return self.sumi
def killTask(self):
""" This function kills the tasks"""
# If the task is still alive kill it
if self.taskHandle != 0:
DAQmxStopTask(self.taskHandle)
DAQmxClearTask(self.taskHandle)
if __name__ == '__main__':
myDaq1 = DAQInput(1, 4, b"cDAQ1Mod1/ai0:3", 200.0, 10.0)
myDaq2 = DAQInput(1, 4, b"cDAQ1Mod2/ai0:3", 200.0, 10.0)
result = myDaq1.getData()
print (result[0:4])
result2 = myDaq2.getData()
print (result2[0:4])
myDaq1.killTask()
myDaq2.killTask()
很可能你的共享對象(在類變量中,例如'sumi')正在消失(但我很快停止了查找,因爲情況並非最小,*症狀*和預期行爲沒有被清楚地描述)。請參見[類__init __()函數內部和外部的變量](http://stackoverflow.com/questions/1537202/variables-inside-and-outside-of-a-class-init-function) – user2246674 2013-04-26 19:50:46