Best practice: Sharing object between different objects

Dave Angel davea at davea.name
Sat Feb 21 09:28:24 EST 2015


On 02/21/2015 07:15 AM, pfranken85 at gmail.com 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.
>

I think you should write the code (or at least a skeleton version).  I 
suspect the answer will become obvious to you, once you're not worrying 
about design patterns, or being java compatible.

Regardless of whether you inherit from a common base class, both classes 
can have an attribute with a "bus object" in it.  The question becomes 
who initializes it, and who decides to reuse the "same one".  Your 
wording doesn't make that the least bit clear to me;  maybe your sample 
code will.

Many times when you'd have a common base class in Java or C++, you just 
have to have a common member or two in Python.

On the other hand, once you start implementing, maybe it'll become 
obvious that there's enough shared code for a common base class.

The first question is whether an ADC "is-a" bus, or "has-a" bus.  Stated 
that way it sounds like you should have an attribute in ADC which is a 
bus object.

> Any hints are highly appreciated!
>
> Thanks!
>


-- 
DaveA



More information about the Python-list mailing list