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>You should store the items directly.  As previously mentioned there is no resource issue with doing it and then it provides the basket with direct access to the items.  Say you wanted to know how much the basket weighs?  well if you add a .weight method to your items class then you can have your basket iterate through all of the items it contains and return the weight of them.  </p>

python oop