Newbie: anything resembling static?
Nick Vargish
nav at adams.patriot.net
Tue Feb 11 18:12:07 EST 2003
phil at dspfactory.com (Phil Rittenhouse) writes:
> I'm thinking about something like a function to send a byte out
> a serial port. The first time it's called it needs to initialize
> the UART, but after that it doesn't.
This problem is exactly where classes will help:
class SerialPort:
__shared_state = {}
def __init__(self, address):
self.__dict__ = self.__shared_state
self.initialized = False
# other stuff to set up the serial port
def send_byte(self, x):
if not self.initialided:
self.initialize()
self.xmit(x)
def initialize(self):
# initialize the UART
self.initialized = True
> If you used this function the way you might use print() for debugging
> purposes, it might be called in hundreds of places in a large project.
> If you wrapped it in a class, you'd have to take care of creating the object
> before anyone calls it and sharing that object around somehow so everyone
> can access it.
That's what the __shared_state bit is all about. It's a "Borg" object;
each time you instantiate a SerialPort object, it will be the same
critter:
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531)
Nick
--
# sigmask.py || version 0.2 || 2003-01-07 || Feed this to your Python.
print reduce(lambda x,y:x+chr(ord(y)-1),'Ojdl!Wbshjti!=obwAqbusjpu/ofu?','')
More information about the Python-list
mailing list