使用 class 计算年龄

Calculating age using a class

我正在尝试编写使用 class 计算年龄的代码,但我对模块和 classes 比较陌生,我很难将值分配给 self

这是我到目前为止所做的:

from datetime import date

class time:
    def __init__(self,time):
        self.time=time

    def function(self):
        today=date.today()
        birthday=today.year-self.year-((today.month,today.day)<(self.month,self.day))
        return birthday

y=time
print (y.function.datetime.date(1994,4,12))

首先,我建议您始终以大写字母开头 类,并使用例如名称 (calculate_age()).

重命名您的函数

最终结果应该是这样的:

from datetime import datetime, date

class Time:
    def __init__(self, date):
        self.date=date

    def calculate_age(self):
        today = datetime.now()
        return today.year - self.date.year - ((today.month, today.day) < (self.date.month, self.date.day))

time = Time(date(1994,4,12))

print(time.calculate_age())

这是您可能会感兴趣的另一种方法。

from datetime import date

class Time:
    def __init__(self, date):
        self.time = date

    def age(self):
        today = date.today()
        date_this_year = date(today.year, self.time.month, self.time.day)
        return today.year - self.time.year - (date_this_year > today)

time = Time(date(1994,4,12))
print(time.age())