【问题标题】:How to create a function inside the class which can tell maximum of an attribute (age) and its corresponding attribute to this max age (i.e. name)?如何在类中创建一个函数,该函数可以将属性(年龄)的最大值及其对应的属性告诉这个最大年龄(即名称)?
【发布时间】:2022-01-15 07:55:27
【问题描述】:
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.')

做完这一切后,我得到以下输出,其中只包含最大年龄,但我还想得到最老的猫的相应名称。我如何将最老的年龄函数放入类中? 比利 2 约翰 3 黑1 最大的猫已经 3 岁了。

我想要的输出 比利 2 约翰 3 黑1 最年长的猫是 3 岁的约翰。

【问题讨论】:

    标签: python class


    【解决方案1】:

    你可以使用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.')
    
    

    【讨论】:

      【解决方案2】:

      您可以使用类属性来跟踪哪只猫是最古老的:

      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
      

      创建一些猫:

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

      检查最老的猫:

      print(Cat.oldest_name, Cat.oldest_age)
      

      它给出:

      John 3
      

      让 Kuro 变老:

      cat3.age = 10
      

      再次检查最老的猫:

      print(Cat.oldest_name, Cat.oldest_age)
      

      它给出:

      Kuro 10
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-29
        • 1970-01-01
        • 2014-07-01
        • 2021-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-23
        相关资源
        最近更新 更多