OOP: best way to code relations between objects of different classes
<p>Let's say we have two classes <code>Basket</code> and <code>Item</code>. Each basket contains a list of items. I can store in the basket the <code>id</code>s of the items, or directly the items objects. Which is the best solution, and why (in terms of memory usage, covenience, etc...)?</p>

<p><strong>CASE A</strong></p>

<pre><code>class Basket(object):

    def __init__(self, basket_name):
        self._name = basket_name
        self._items = []


    def add_item(self, item_id)
        self._items.append(item_id)


class Item(object):

    def __init__(self, item_id):
        self._id= item_id

&gt;&gt;&gt; b = Basket('My_Basket')
&gt;&gt;&gt; i1 = Item(1)
&gt;&gt;&gt; i2 = Item(2)
&gt;&gt;&gt; b.add_item(1)
&gt;&gt;&gt; b.add_item(2)
</code></pre>

<p><strong>CASE B</strong></p>

<pre><code>class Basket(object):

    def __init__(self, basket_name):
        self._name = basket_name
        self._items = []


    def add_item(self, item)
        self._items.append(item)


class Item(object):

    def __init__(self, item_id):
        self._id= item_id


&gt;&gt;&gt; b = Basket('My_Basket')
&gt;&gt;&gt; i1 = Item(1)
&gt;&gt;&gt; i2 = Item(2)
&gt;&gt;&gt; b.add_item(i1)
&gt;&gt;&gt; b.add_item(i2)
</code></pre>

<p>Option B is usually the best option because this is how <strong>Object Oriented Programming</strong> works. Because you are using the objects directly you can also access them directly in you code. If you use the link option then in order to access a given <code>Item</code> later you would have to do some sort of query to find that object. When you use the object directly what python essentially does is creates that link for you. The object is not copied twice but instead it is referenced in the <code>_items</code> list inside your <code>Basket</code> object.</p>

<p>Also, the <code>self._id= item_id</code> in</p>

<pre><code>def __init__(self, item_id):
    self._id= item_id
</code></pre>

<p>would not be required because you would have no need to find that id, and hence:</p>

<pre><code>&gt;&gt;&gt;i1 = Item(1)
&gt;&gt;&gt;i2 = Item(2)
</code></pre>

<p>Would simply become:</p>

<pre><code>&gt;&gt;&gt; i1 = Item()
&gt;&gt;&gt; i2 = Item()
</code></pre>

python oop