[英]Python Programming with Class Definition
到目前為止,這是我的代碼,到目前為止我遇到的錯誤是 (name 'person' is not defined) on line person.name = name
,我真的被卡住並試圖找出問題/錯誤是什么我的代碼必須基於我在下面寫的問題。我不確定我的其余代碼是否有任何錯誤,因為它首先檢測到該錯誤。
from datetime import date
class person:
pass
def create_person(name, height, birthdate):
person.name = name
person.height = height
get_age = birthdate
return person
def get_age(person):
birthdate = person.birth
today = date.today()
subyear = 0
if today.month < birthdate.month or (today.month == birthdate.day and today.day <= birthdate.day):
subyear = 1
person.age = (today.year - (birthdate.year + subyear))
return person.age
def get_description(person):
return person.name + ' is ' + str(person.height) + ' cm high and is ' + str(get_age(person)) + ' years old'
def main():
birthdate = date(1976, 8, 14)
person = create_person('Michael', 190, birthdate)
print(get_description(person))
這是問題:
為 Person class 編寫 class 定義,並使用這些 function 頭文件編寫用戶定義的函數:
def create_person(name, height, birthdate): # Return aa new person object with the given name, height and birthdate. # - name is a str # - height is an int object in centimetres # - birthdate is a date object from the # module datetime
def get_age(person): # Return the age of the person in years.
例如,假設今天的日期是 2018 年 6 月 12 日。如果 Mary 出生於 2017 年 6 月 4 日,那么 Mary 的年齡是 1。但是,如果 Bob 出生於 2018 年 6 月 14 日,那么 Bob 還沒有過第一個生日所以年齡為0。
def get_description(person): # Return a string object of the form: Name is # N cm high and is M years old, where N and M # are integers
例如,邁克爾身高 190 厘米,現年 43 歲,或者薩曼莎身高 95 厘米,現年 4 歲。
def main(): # Create a person named 'Michael', with height # 190 cm, who was born on August 14, 1976 and # output a description of this individual.
如果在編寫 function 時使用來自導入模塊的 function,則通常在代碼頂部聲明導入語句。
這是一個只調用主 function 的主程序的示例運行。
Michael is 190 cm high and is 43 years old.
這是我目前收到的提示:
使用 datetime 模塊中的日期 class 來表示日期。 類型為日期的 object 具有可用於計算人員年齡的年、月和日屬性。
要計算一個人的當前年齡,您需要首先計算今天的日期。 在 datetime 模塊的日期 class 中有一個方法可以創建一個新的日期 object 來表示當前日期。 這種方法的名稱是今天。 但是,此方法的特殊參數必須是日期 class 本身,而不是類型為日期的特定 object。 應用於 class object 而不是該 class 的實例的方法稱為 ZA2F2ED4F8EBC2CBB4C21A29DC4 方法。
因此,要創建當前日期,您可以使用以下表達式:
date.today()
因為從 datetime 模塊導入日期 class 后,標識符 date 綁定到日期 class object。
要計算年齡,您只需從當前日期的年份屬性中減去出生日期的年份屬性即可。 但是,您還需要檢查此人今年是否已經過生日,如果沒有,則減去一年
讓Person
創建自己的屬性
class Person:
def __init__(self, name, height, birthdate):
self.name = name
self.height = height
self.birthdate = birthdate
# why someone would write such a function is beyond me, but...
def create_person(name, height, birthdate):
return Person(name, height, birthdate)
# test
p = create_person('myname', 100, '23-23-23')
print(p.name)
這產生
myname
現在其他函數將擁有一個可以使用的 class 實例。
如果您對其中任何一個功能有疑問,最好將其發布在另一個僅關注該問題的問題中。 (刪除不需要演示問題的功能/方法)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.