Newbie: anything resembling static?

Phil Rittenhouse phil at dspfactory.com
Wed Feb 12 10:15:38 EST 2003


Coooool.

I hadn't quite grok'd that the class variables were shared
among all instances.  That makes things much easier.

Thanks!
Phil


Nick Vargish <nav at adams.patriot.net> wrote in message news:<yyy7kc6h0oo.fsf at adams.patriot.net>...
> 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




More information about the Python-list mailing list