亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Python 函數中返回類實例

如何在 Python 函數中返回類實例

呼啦一陣風 2022-12-06 15:10:29
本周我遇到了課堂挑戰,雖然我返回了正確的年齡,但我沒有按照說明返回課堂實例。我讀過這篇文章,但 python 2.7 語法似乎完全不同。導師的筆記。該類已正確實現,并且您已正確創建其實例。但是當你試圖找到最老的狗時,你只返回它的年齡,而不是實際的實例(按照說明)。該實例不僅保存有關年齡的信息,還保存有關姓名的信息。一個小評論:您從格式化字符串內部調用函數“oldest_dog”——這是非常規的,您最好在此之前的行上執行該函數,并在格式化字符串中僅包含計算變量。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 max age instancedef oldest_dog(dog_list):    return max(dog_list)# inputdog_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.")
查看完整描述

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)


查看完整回答
反對 回復 2022-12-06
  • 1 回答
  • 0 關注
  • 262 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號