1 回答

TA貢獻1853條經驗 獲得超18個贊
我已經更改了您的代碼以顯示如何返回實例:
class Dog:
# constructor method
def __init__(self, name, age):
self.name = name
self.age = age
# three class instance declarations
maxx = Dog("Maxx", 2)
rex = Dog("Rex", 10)
tito = Dog("Tito", 5)
# return the dog with the max age
def oldest_dog(dog_list):
return max(dog_list, key=lambda x: x.age) # use lambda expression to access the property age of the objects
# input
dogs = [maxx, rex, tito]
# I changed this as per instructor's notes.
dog = oldest_dog(dogs) # gets the dog instance with max age
print(f"The oldest dog is {dog.age} years old.")
輸出:
The oldest dog is 10 years old.
編輯: 如果不允許使用 lambda,則必須遍歷對象。這是一個沒有函數 lambda 的實現oldest_dog(dog_list):
# return max age instance
def oldest_dog(dog_list):
max_dog = Dog('',-1)
for dog in dog_list:
if dog.age > max_dog.age:
max_dog = dog
編輯 2: 正如@HampusLarsson 所說,您還可以定義一個返回屬性的函數,age并使用它來防止使用 lambda。這里有一個版本:
def get_dog_age(dog):
return dog.age
# return max age instance
def oldest_dog(dog_list):
return max(dog_list, key= get_dog_age)
添加回答
舉報