【发布时间】:2020-01-14 00:45:27
【问题描述】:
我是新来的,也是 Python 的新手。我的同事有一些 C/C++。我正在 udemy 上课程,我想知道是否有更好的想法来解决基于一个值查找类对象数组的元素的问题。课程任务是寻找“最古老的猫”。解决方案只是不使用列表/数组,但我想知道如何对对象数组进行操作,以及是否有比我的静态方法 getoldest 更好的选择,因为对我来说似乎我正在尝试“欺骗”python。
class Cat:
def getoldest(Cat=[]):
age_table=[]
for one in Cat:
age_table.append(one.age)
return Cat[age_table.index(max(age_table))]
def __init__(self, name, age):
self.name = name
self.age = age
# 1 Instantiate the Cat object with few cats
kotki3=[]
kotki3.append(Cat("zimka", 5))
kotki3.append(Cat("korek", 9))
kotki3.append(Cat("oczko", 10))
kotki3.append(Cat("kotek", 1))
kotki3.append(Cat("edward", 4))
# 2 Create a function that finds the oldest cat
oldest = Cat.getoldest(kotki3)
# 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2
print(f'The oldest cat is {oldest.name} and it\'s {oldest.age} years old')
非常感谢。
【问题讨论】:
-
更直接的方法是在 cat 对象列表中使用
max():oldest = max(kotki3, key=lambda x: x.age) -
术语注释:这是一个列表,而不是一个数组。请注意,您的列表中没有“类对象”,类对象将是 类本身(它们是 Python 中的第一类对象,几乎所有东西都是 Python 中的对象)。列表中有你的类的实例。
标签: python arrays class methods