abhiieor
abhiieor

Reputation: 3554

Python class data member as object of another class

I am making two different related classes (store and item). Idea is to associate items selling in a store instance:

class store:   
    def __init__(self, co_loc_i, co_loc_ref_i, lat, lon, items=None):
      self.lat = lat
      self.lon = lon
      self.co_loc_i = co_loc_i
      self.co_loc_ref_i = co_loc_ref_i
      self.items = items or []

    def addItem(self, item):
        self.items.append(item)

    def getItems(self):
        return self.items

class Item:
    def __init__(self, mdse_item_i, dept, clas, sbcl, mdse_item_ref_i):
      self.mdse_item_i = mdse_item_i
      self.dept = dept
      self.clas = clas
      self.sbcl = sbcl
      self.mdse_item_ref_i = mdse_item_ref_i

Then I am doing objects instantiation of these classes to use:

i1 = Item(1,1,1,1,1)
i2 = Item(2,1,1,1,2)
i3 = Item(3,1,1,1,3)
s1= store(10, 10, 1.1, 1.1)
s2= store(20, 20, 1.2, 1.2)

After this I associate items with store instances (I checked in here that i1,i2,i3 are Item class instances :

s1.addItem([i1,i2])
s2.addItem([i2,i3])

However when iterating over items inside a store I get type of x as list in following code:

for x in s1.getItems():
    print(type(x))

<type 'list'> How can I make sure that x here is item class object so that I can call item class methods.

Upvotes: 0

Views: 770

Answers (1)

cco
cco

Reputation: 6281

You're seeing a list because that's what you passed in:

s1.addItem([i1,i2])
s2.addItem([i2,i3])

If you want Item instances in the store, pass those instead:

s1.addItem(i1)
s1.addItem(i2)
s2.addItem(i2)
s2.addItem(i3)

if you want to be able to add lists of items, you could define another function:

def addItems(self, items):
    self.items.extend(items)

The key difference is extend vs append.

Upvotes: 1

Related Questions