如何在 Python 函数中返回类实例

本周我遇到了课堂挑战,虽然我返回了正确的年龄,但我没有按照说明返回课堂实例。我读过这篇文章,但 python 2.7 语法似乎完全不同。

导师的笔记。

该类已正确实现,并且您已正确创建其实例。但是当你试图找到最老的狗时,你只返回它的年龄,而不是实际的实例(按照说明)。该实例不仅保存有关年龄的信息,还保存有关姓名的信息。一个小评论:您从格式化字符串内部调用函数“oldest_dog”——这是非常规的,您最好在此之前的行上执行该函数,并在格式化字符串中仅包含计算变量。

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 max age instance

def oldest_dog(dog_list):

    return max(dog_list)


# input

dog_ages = {maxx.age, rex.age, tito.age}


# I changed this as per instructor's notes.

age = oldest_dog(dog_ages)

print(f"The oldest dog is {age} years old.")


呼啦一阵风
浏览 249回答 1
1回答

慕容森

我已经更改了您的代码以显示如何返回实例:class Dog:    # constructor method    def __init__(self, name, age):        self.name = name        self.age = age# three class instance declarationsmaxx = Dog("Maxx", 2)rex = Dog("Rex", 10)tito = Dog("Tito", 5)# return the dog with the max agedef oldest_dog(dog_list):    return max(dog_list,  key=lambda x: x.age)  # use lambda expression to access the property age of the objects# inputdogs = [maxx, rex, tito]# I changed this as per instructor's notes.dog = oldest_dog(dogs)     # gets the dog instance with max ageprint(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 instancedef 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 instancedef oldest_dog(dog_list):    return max(dog_list,  key= get_dog_age)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python