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)
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.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다