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>I would prefer storing objects, not IDs. Because each time you would have to do something with your Items you would have to first somehow get/load this object by ID. But this is a general case.</p>

<p>In case of you will have tons of Items and no operations with full list (e.g. basket will only perform actions on a single object, not on full collection) you might want to store only IDs.</p>

python oop