Home > Net >  Python: How to identify a class using a label?
Python: How to identify a class using a label?

Time:05-11

The code I am working on has a class called cell, an object which carries a label attribute. The snippet of code looks as follows:

class Cell:
  def init(self, label):
    self.label = label

Later in the code I have a list of cell objects, each of them carrying a unique label. Is there way to, given a specific label, find the corresponding cell object?

CodePudding user response:

If you do not want to check if you are working on a list (like this case) and just want to loop through your list to find your object you can use a for loop like so:

cell_by_label = []
for cell in cell_list:
    if cell.label == "hello":
             cell_by_label.append(cell)


CodePudding user response:

If you want to pick the right one by label, why do not you create a dictoinary of cells instead of a list? Then it is easy to extract the wished one: mycell = cell_d['wished_label']. But otherwise it is not too complicated either:

for cell in cell_list:
    if cell.label == 'wished_label':
        mycell = cell
        break

CodePudding user response:

You could elaborate your Cell class to facilitate an index search. Something like this:

class Cell:
    def __init__(self, label):
        self.label = label
    def __eq__(self, other):
        if isinstance(other, str):
            return self.label == other
        if isinstance(other, Cell):
            return self.label == other.label
        return False
    def __repr__(self):
        return self.label

cell_list = [Cell('H'), Cell('O')]

print(cell_list.index(Cell('O')))
print(cell_list.index('H'))

Output:

1
0

Note:

As with any other list index operation, if an item is not found, ValueError will be raised

  • Related