提问人:Andelib Sriz 提问时间:10/24/2023 最后编辑:SayseAndelib Sriz 更新时间:10/24/2023 访问量:53
为什么我收到错误“AttributeError: 'float' object has no attribute 'year'”
Why am I getting the error "AttributeError: 'float' object has no attribute 'year'"
问:
问题:编写一个 Python 程序来创建一个 person 类。包括姓名、国家/地区和出生日期等属性。实现确定此人的年龄的方法。
我的解决方案:
from datetime import date
class Person:
def __init__(self, name, country, date_of_birth):
self.name = name
self.country = country
self.date_of_birth = date_of_birth
def calculate_age(self):
today = date.today()
age = today.year - self.date_of_birth.year
if today < date(today.year, self.date_of_birth.month, self.date_of_birth.day):
age -= 1
print(age)
person = Person(name="Jack", country="USA", date_of_birth=1997/10/13)
person.calculate_age()
我希望代码显示此人的年龄。
答: 暂无答案
评论
1997/10/13
不是日期,而是数学除法,你已经知道如何使日期在函数中变得明显date_of_birth=1997/10/13
传递为15.3615384615
date_of_birth
today.year
date_of_birth.month
date_of_birth.day
age = -1
age -= 1
age