how to select an object from a list of objects by its attribute in python

前端 未结 4 1084
北荒
北荒 2021-02-13 22:29

Apologies if this question has already been asked but I do not think I know the correct terminology to search for an appropriate solution through google.

I would like to

4条回答
  •  灰色年华
    2021-02-13 23:01

    The missing underscore makes plist a public property. I don't think that's what you want, since it does not encapsulate the functionality and you could call a.plist.append instead of a.addPerson.

    class Example():
       ...
       def filter(self, criteria):
           for p in self.plist:
               if criteria(p):
                   yield p
    
       def getByNum(self, num):
            return self.filter(lambda p: p.num == num)
    
    dave = next(a.getByNum(123))
    

    If the numbers are unique, you may also consider using a dictionary that maps from number to name or person instead of a list. But that's up to your implementation.

提交回复
热议问题