[英]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)?
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.完成这一切之后,我得到了以下 output ,其中只包含最大年龄,但我还想获得最老的猫的相应名称。 How do i put is oldest-age function inside the class?
我如何将最旧的 function 放入 class 中? Billy 2 John 3 Kuro 1 The oldest cat is 3 years old.
Billy 2 John 3 Kuro 1 最老的猫是 3 岁。
WHAT I WANT AS OUTPUT Billy 2 John 3 Kuro 1 The oldest cat is John which is 3 years old.我想要什么 OUTPUT Billy 2 John 3 Kuro 1 最老的猫是 3 岁的 John。
You could use functools.reduce
:你可以使用
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.')
You can use class attributes to keep track which cat is the oldest:您可以使用 class 属性来跟踪哪个猫是最古老的:
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:让 Kuro 变老:
cat3.age = 10
Check for the oldest cat again:再次检查最老的猫:
print(Cat.oldest_name, Cat.oldest_age)
It gives:它给:
Kuro 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.