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

问题描述 投票:0回答:1

我本周遇到了课堂挑战,尽管我返回了正确的年龄,但我没有按照说明返回课堂实例。我读过this post,但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.")
python function class instance return-type
1个回答
3
投票

我已更改您的代码以显示如何返回实例:

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)
© www.soinside.com 2019 - 2024. All rights reserved.