1

私は別のデータ取得プロジェクトに取り組んでいますが、これはオブジェクト指向プログラミングの質問になりました。コードの下部にある「main」で、オブジェクト DAQInput の 2 つのインスタンスを作成します。これを書いたとき、メソッド .getData は特定のインスタンスの taskHandle を参照すると思っていましたが、そうではありません。実行すると、コードは最初のハンドルで getData タスクを 2 回実行するため、明らかに Python でのオブジェクト指向プログラミングをよく理解していません。申し訳ありませんが、このコードは PyDAQmx と National Instruments ボードが接続されていないと実行できません。

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()
4

1 に答える 1

3

これらの変数:

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]

クラス変数です。これらはクラス自体に属し、クラスのインスタンス間で共有されます (つまり、 で変更するとself.dataInstance1も変更されます)。Instace2self.data

それらをインスタンス変数にしたい場合は、 で定義します__init__

于 2013-04-26T19:54:07.760 に答える