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.')
完成所有這些操作后,我得到以下輸出,其中僅包含最大年齡,但我還想獲得最老的貓的相應名稱。我如何在課堂上放置最古老的功能? Billy 2 John 3 Kuro 1 最老的貓是 3 歲。
我想要的輸出 Billy 2 John 3 Kuro 1 最老的貓是 John,它是 3 歲。
uj5u.com熱心網友回復:
你可以使用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.')
uj5u.com熱心網友回復:
您可以使用類屬性來跟蹤哪只貓是最古老的:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/412584.html
標籤:
上一篇:如何將自定義類串列轉換為二維陣列
下一篇:在SQLServer2019中將dd/mm/yyyyhh:mm:ssam/pm轉換為yyyy/mm/ddhh:mm:ss
