为什么我收到错误“AttributeError: 'float' object has no attribute 'year'”

Why am I getting the error "AttributeError: 'float' object has no attribute 'year'"

提问人:Andelib Sriz 提问时间:10/24/2023 最后编辑:SayseAndelib Sriz 更新时间:10/24/2023 访问量:53

问:

问题:编写一个 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()

我希望代码显示此人的年龄。

python 属性错误

评论

3赞 Sayse 10/24/2023
1997/10/13不是日期,而是数学除法,你已经知道如何使日期在函数中变得明显
0赞 DeepSpace 10/24/2023
date_of_birth=1997/10/13传递为15.3615384615date_of_birth
0赞 Sembei Norimaki 10/24/2023
也看看有条件的,你正在和 .在条件内,您可能想要(对于尚未出生的人)而不是today.yeardate_of_birth.monthdate_of_birth.dayage = -1age -= 1
0赞 Andelib Sriz 10/24/2023
好的,我解决了,谢谢你的帮助
0赞 slothrop 10/24/2023
@SembeiNorimaki条件实际上是“如果今天早于今年的生日,则将计算出的年龄减去 1”。例如,如果此人出生于 1997 年,则初始计算为 2023-1997 = 26。条件是,如果今天是 2023-10-24,那么 1997-10-24 之后出生的人是 25 岁,而不是 26 岁。age

答: 暂无答案