python - Programming with connected hardware -



python - Programming with connected hardware -

i think demonstrated example, question general one. using library pyvisa, interfaces gpib devices program. have set python class each instrument, powerfulness supply, might have this:

import visa class powersupply: def __init__(self): rm = visa.resourcemanager() self.ps = rm.open_resource('gpib0::12::instr') def getvoltage(self): homecoming self.ps.ask('volt?') def setvoltage(self,v): self.ps.write('volt '+str(v)) ... ps = powersupply() ps.setvoltage(10)

unfortunately, there chance rm.open_resource function may not work, or might homecoming none if device not exist @ address (in code wrote function did instead). question is: best practice coding class powersupply? 1 write exceptions every method test if self.ps exists/is not none, seems there must improve way. there?!

one write exceptions every method test if self.ps exists/is not none, seems there must improve way. there?!

yes. way you've written code, if self.ps ever none, it's going none start, , never alter again. so, instead of testing in every method, test once:

def __init__(self): rm = visa.resourcemanager() self.ps = rm.open_resource('gpib0::12::instr') if self.ps none: raise powersupplyexception('unable open resource gpib0::12::instr')

now, code constructs powersupply has either handle exception or prepared propagate it, question implies open_resource might raise exception anyway, can't problem. besides, seems right place handle it—at top level of program, wherever you're creating powersupply in response gui or cli or network command, that's you're prepared handle beingness unable create it, right?

and code uses already-constructed powersupply doesn't have worry about. know self.ps not none or couldn't have gotten object constructor.

python class exception hardware hardware-interface

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -