0

Good afternoon dear colleagues! I have maybe quite an obvious question, but it can be considered as quite a mystery to me.

So, I have two custom classes, let it be Class A and Class B. Class B has a property, which contains multiple instances of Class A. It also contains methods to work with this property: add, remove, get single and all instances in this property.

However, apart from standard and quite over questioned deal with MVC pattern, I wonder: what is the most efficient and fast method to remove an object from this property (array) in Python, which implements some customization (e.g. compare objects by id, title and other properties).

I had implemented my own, but it seems way too complicated for such an essential operation.

class Skill:

    def __init__(self, id_):
        self.id = id_

class Unit:

    def __init__(self):
        self.skills = []

    def get_skills(self):
        return self.skills

    def get_skill(self, index):
        return self.skills[index]

    def add_skill(self, skill):
        self.skills.append(skill)

    def remove_skill(self, skill_to_remove):
        self.skills = filter(lambda skill: skill.id != skill_to_remove.id, self.skills)
jujka
  • 1,190
  • 13
  • 18

1 Answers1

1

If you need arbitrary criteria, then filtering is OK, but it is slightly shorter to use a list comprehension. For example, instead of

self.skills = filter(lambda skill: skill.id != skill_to_remove.id, self.skills)

use:

self.skills = [s for s in self.skills if s.id != skill_to_remove.id]

It's also possible to modify the list in-place (see this question) using slice assignment:

self.skills[:] = (s for s in self.skills if s.id != skill_to_remove.id)

If you are filtering skills based on an exact match with a "template" skill, i.e. matching all the properties of skill_to_remove then it might be better to implement an equality method for your Skill class (see this question). Then you could just use the remove method on self.skills. However, this will only remove the first matching instance.

Community
  • 1
  • 1
DNA
  • 42,007
  • 12
  • 107
  • 146
  • Thank you very much for your assistance! That resolved some hesitation of mine ;) – jujka Mar 31 '15 at 13:56
  • Glad it helped - please consider accepting my answer using the "tick" button on the left! ;-) – DNA Mar 31 '15 at 14:28