Home > Net >  How to create a function inside the class which can tell maximum of an attribute (age) and its corre
How to create a function inside the class which can tell maximum of an attribute (age) and its corre

Time:01-15

class Cat:
    species = 'mammal'
    def __init__(self, name, age):
        self.name = name
        self.age = age

cat1 = Cat('Billy', 2)
cat2 = Cat('John', 3)
cat3 = Cat('Kuro', 1)
print(cat1.name, cat1.age)
print(cat2.name, cat2.age)
print(cat3.name, cat3.age)

def oldest_age(*args):
    return max(args)
print(f'The oldest cat is {oldest_age(cat1.age, cat2.age, cat3.age)} years old.')

After doing all this, I get the following output which contains just the maximum age, but I want to also get the corresponding name of the cat which is the oldest. How do i put is oldest-age function inside the class? Billy 2 John 3 Kuro 1 The oldest cat is 3 years old.

WHAT I WANT AS OUTPUT Billy 2 John 3 Kuro 1 The oldest cat is John which is 3 years old.

CodePudding user response:

You could use functools.reduce:

from functools import reduce

def oldest_age(*cats):
    return reduce(lambda x, y: x if x.age > y.age else y, cats)

oldest_cat = oldest_age(cat1, cat2, cat3)
print(f'The oldest cat is {oldest_cat.name}, whose age is {oldest_cat.age} years old.')

CodePudding user response:

You can use class attributes to keep track which cat is the oldest:

class Cat:
    oldest_name = None
    oldest_age = None
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    @property
    def age(self):
        return self._age
    
    @age.setter
    def age(self, val):
        self._age = val
        cls = self.__class__
        if  cls.oldest_age is None or self._age > cls.oldest_age:
            cls.oldest_age = self.age
            cls.oldest_name = self.name

Create some cats:

cat1 = Cat('Billy', 2)
cat2 = Cat('John', 3)
cat3 = Cat('Kuro', 1)

Check for the oldest cat:

print(Cat.oldest_name, Cat.oldest_age)

It gives:

John 3

Make Kuro older:

cat3.age = 10

Check for the oldest cat again:

print(Cat.oldest_name, Cat.oldest_age)

It gives:

Kuro 10
  •  Tags:  
  • Related