Home > Software design >  how to return a list of class parameter?
how to return a list of class parameter?

Time:09-17

class animal():
  def__init__(self, name, species, legs):
     self.name = name
     self.breed = species
     self.legs = legs
  def__eq__(self, other):
     return self.breed == other.species and self.name == other.name
  def__repr__(self):
     return f"{self.name}: {self.speies}: {self.legs}"

def leg_count(animals, multiple):
    return 

Above class, how to return a list of name that have number of legs are greater than 4??

group1 = animal("Adam","dog",4)
gruop2 = animal("Besty","cat", 4)
group3 = animal("Alex","bird", 2)
animals = [group1, group2, group3]
leg_count(animals, 4)

and also is it possible with one line?

CodePudding user response:

class animal:
    def __init__(self, name, species, legs):
        self.name = name
        self.breed = species
        self.legs = legs

    def __eq__(self, other):
        return self.breed == other.species and self.name == other.name

    def __repr__(self):
        return f"{self.name}: {self.breed}: {self.legs}"


def leg_count(animals, multiple):
    result = [item.name for item in animals if item.legs >= multiple]
    return result

Above class returns animal object and leg_count function returns a list that contains object.name which has greater or equal amount of legs you specify in multiple value. For Example:

group1 = animal("Adam", "dog", 4)
group2 = animal("Besty", "cat", 4)
group3 = animal("Alex", "bird", 2)
animals = [group1, group2, group3]
print(leg_count(animals, 4))

output is :

['Adam', 'Besty']

CodePudding user response:

To briefly answer your question using list comprehension, consider the following solution:

def leg_count(animals, multiple):
    return [a.name for a in animal if a.legs > multiple]

Besides that, you seem to have a problem in your __eq__ and __repr__ methods, namely, there is no species attribute, I think you mean to access the attribute breed.

  • Related