使用班级计算年龄

问题描述 投票:0回答:2

我正在尝试编写使用类计算年龄的代码,但我对模块和类相对较新,并且我很难将值赋给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))
python function module self
2个回答
0
投票

这是另一种方法,你可能会觉得有趣。

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())

1
投票

首先,我建议您始终使用大写字母开始您的类,并使用例如名称(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())

© www.soinside.com 2019 - 2024. All rights reserved.