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><strong>everything</strong> in python is an object, including integers used as IDs for other objects. So in both Case A and Case B you are appending references to objects to the <code>Basket._items</code> list.</p>

<p>So what is the difference between A and B? If you only store the IDs then how will you reference the original objects? It is harder to guarantee that they will exist in the namespace. Any code that looks up properties from <code>item</code> instances may fall into that trap.</p>

python oop