Best practice: Sharing object between different objects
Rob Gaddi
rgaddi at technologyhighland.invalid
Mon Feb 23 13:10:20 EST 2015
On Sat, 21 Feb 2015 04:15:50 -0800, pfranken85 wrote:
> Hello!
>
> I have a best-practice question: Imagine I have several hardware devices
> that I work with on the same I2C bus and I am using the python smbus
> module for that purpose. The individual devices are sensors, ADC, DAC
> components. As I said, I would like to derive the corresponding classes
> from one common class, let's say I2CDevice, so that they can share the
> same bus connection (I don't want to do a import smbus, ..., self.bus =
> smbus.SMBus(1) all the time). Of course, I could just pass the the bus
> reference to each instance, but I am pretty sure that there must be a
> nicer way to do this.
>
> In particular, I imagine the following: It should be possible that I
> have two classes, ADC_I2C, DAC_I2C which share the same base class. Once
> I create an instance of ADC_I2C or DAC_I2C it should check whether a bus
> object exists, if not, it should create one and the other class should
> be able to use this bus reference as well. Do you get my point? I am
> pretty sure that such a design pattern should exist, maybe also in the
> reference of DB connections? Unfortunately I did not find something like
> this.
>
> Any hints are highly appreciated!
>
> Thanks!
So my experience doing similar work is with VMEBus, but if I were trying
to do what you're doing, I'd take advantage of the fact that hardware
isn't nearly as abstract as software. SMBus(1) represents three physical
contiguous pieces of copper on a PCB somewhere.
So I'd solve it with module level global variables. It's semi-frowned
upon on software stuff because it creates an unintentional shared state
between different modules, but you really HAVE a shared state, so it
needs to be dealt with.
So I'd put your ADC and DAC in the same package, whether all in one file
or all in a package folder, and I'd give that package a:
def getSMBus(busnumber):
that takes care of the management of only creating each bus once.
Then I'd give each class a:
def __init__(busnumber):
self.bus = getSMBus(busnumber)
You could commonize that by deriving both classes from a common ancestor
(all my VME modules derive from a common Region), but with only one piece
of shared code between I don't think I'd bother. If you did, you could
make the getSMBus code a classmethod just to make clear the lack of
dependency on individual instances, but that starts to be code for code's
sake.
--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order. See above to fix.
More information about the Python-list
mailing list