Simple Python class questions

Terry Reedy tjreedy at udel.edu
Fri Jun 20 03:24:31 CEST 2008



John Dann wrote:
> 
> Let's say I define the class in a module called comms.py. The class
> isn't really going to inherit from any other class (except presumably
> in the most primitive base-class sense, which is presumably automatic
> and implicit in using the class keyword). Let's call the class
> serial_link. So in comms.py I have:

If you on only ever going to have 1 serial link, you could put all 
functions in the module.  But the class allows for multiple links in 
some future usage.

> class serial_link:

Recommended for class names would be SerialLink, I believe (see PEP 8)
but at least a cap for the initial letter of python-defined classes.

> 	def __init__(self):
> 		Try
> 			Import serial # the pyserial library
> 		Except ImportException
> 			#Error handling

The import should be at module level.  You only want to do it once, not 
for every link.  And if the import fails, you should find out right 
away.  You perhaps should move try/except into the importing module.  Or 
re-raise the exception.  Either way, the import of this module should 
fail if it cannot get serial.

> 	def openPort(self):
> 		Try
> 			#Code to try opening serial port
> 			Return "Success"
> 		Except SerialException
> 			Return "Failure"

I would either move this to __init__ or call it from there (but the 
latter only if you expect to close and reopen ports.


> Then in my separate main calling module I might have:
> 
> Import comms

I guess you learned by now why cut/paste/edit-down is superior to 
re-typing ;-)

> serlink=comms.seral_link

....()

      #Create instance of serial_link class
> print serlink.openPort

....()

Terry Jan Reedy




More information about the Python-list mailing list