如何 return class 函数中的实例 Python

How to return the class instance in a function in Python

我这周遇到了 class 挑战,虽然我 return 设置了正确的年龄,但我没有按照说明 return class 实例。我读过 但 python 2.7 语法似乎完全不同。

教师笔记。

The class is implemented correctly, and you create its instances correctly. But when you try to find the oldest dog, you return only its age, not the actual instance (as per instructions). The instance holds the information not only on the age, but also on the name. A minor comment: you call the function "oldest_dog" from inside the formatted string - this is unconventional, you'd better execute the function on the line before that and include only the calculated variable inside the formatted string.

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.")

我已经更改了您的代码以展示您如何 return 个实例:

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,则必须遍历对象。这是一个没有函数 oldest_dog(dog_list):

的 lambda 的实现
# 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 所说,您还可以定义一个 return 是 属性 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)