Cbfed
Cbfed

Reputation: 11

Return all instances of a class that meet a criterion

I'm completely new to Python so I may not be asking this in the right way and I have tried to find an answer (unsuccessfully, obviously).

I am trying to set up a class and then to find all instances of the class that meet a certain criterion. I don't know if a class is the right way to go about this so open to all advice (even if it takes me away from classes).

For a simple example (see code below) if I wanted to find all Employee's who are over 30 would the right approach be to make a class method? In reality you'd have DOB rather than age but for simplicity I've gone with age. I'd also want some sort of variable so that I could change 30 to let's say 50.

class Employee:
  def __init__(self, name, age):
    self.name = name
    self.age = age

e1 = Employee("John", 36)
e2 = Employee("Sally", 21)
e3 = Employee("Jamie", 53)

What is the "right" way or efficient way to achieve this? For this example above for ages above 30 I'd want the e1 and e3 instances. Any help would be appreciated!

Upvotes: 1

Views: 192

Answers (2)

U13-Forward
U13-Forward

Reputation: 71600

Or also modify the class:

class Employee:
  def __init__(self, name, age):
    self.name = name
    self.age = age
    self.age_over_30 = self.age > 30

l = [Employee("John", 36), Employee("Sally", 21), Employee("Jamie", 53)]
print([i.name for i in l if i.age_over_30])

Or if you would modify the age attribute, make the class:

class Employee:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  @property
  def age_over_30(self):
      return self.age > 30

Upvotes: 0

Mark
Mark

Reputation: 92450

You would typically have your instances in some sort of collection like a list rather than individual variables. You could then filter your list or use a list comprehension to get the elements in the list you want. Here's an example with a list comprehension:

class Employee:
    def __init__(self, name, age):
        self.name = name
        self.age = age

employees = [
    Employee("John", 36),
    Employee("Sally", 21),
    Employee("Jamie", 53)
]

over_thirty = [e for e in employees if e.age > 30]

for e in over_thirty:
    print(e.name)

prints:

John
Jamie

You can avoid the extra list over_thirty and iterate directly over the filter results for the same result:

for e in filter(lambda e: e.age > 30, employees):
    print(e.name)

Upvotes: 4

Related Questions