**更新**基于用户定义方法的Python编程
有人能帮我输入正确的代码吗?我还没弄明白**更新**基于用户定义方法的Python编程,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,有人能帮我输入正确的代码吗?我还没弄明白 我已经发布了下面的代码和下面收到的错误结果。有些年龄报告不正确。有人能帮我输入正确的代码吗?感谢您的时间和提供的任何帮助 下面有人帮我算出了他们的生日 (莎拉=2000/08/01,埃里克=2009/08/02,卡特=2009/07/28,佐治亚=2005/09/01) 代码如下: from datetime import date class Person: def __init__(self, name, birthdate): s
我已经发布了下面的代码和下面收到的错误结果。有些年龄报告不正确。有人能帮我输入正确的代码吗?感谢您的时间和提供的任何帮助 下面有人帮我算出了他们的生日 (莎拉=2000/08/01,埃里克=2009/08/02,卡特=2009/07/28,佐治亚=2005/09/01)
代码如下:
from datetime import date
class Person:
def __init__(self, name, birthdate):
self.name = name
self.birthdate = birthdate
def get_age(self):
birthdate = self.birthdate
today = date.today()
if today.month >= birthdate.month and today.day >= birthdate.day:
self.age = (today.year - birthdate.year)
else:
self.age = (today.year - birthdate.year) - 1
return self.age
这是结果(一些年龄测试失败):
我想您在
get\u age()
中有一个逻辑错误:
最好尝试将代码精简到引起问题的特定部分,使问题更加集中。看@CrazyChucky好的,没问题。我不知道,但谢谢你通知我更新了我的帖子,只包含代码,错误
today.month>=birthdate.month或today.day>birthdate.day
可能不是你想要的。将今天的7月31日与出生日期8月15日进行比较时,它的计算结果为True
。我会计算和比较自Unix时代以来朱利安的天数或秒数,但这实际上取决于老师的期望。如果你能把作业的完整内容放到你的问题中,那会有帮助。一个单独的If
创建并设置self.age
如果为真,但根本不创建self.age
如果为假,这也不是你想要的。我确实想相信它是get\u age(self)
,我只是不确定在哪里改变。我用“>=”和“and”两个词都试过了,但都不起作用。在你的else情况下,我得到了同样的结果,我想你的意思是有subyear=1
和birthdate.year+subyear
——对不起,我以前一定是误读了。编辑:我更新了我的评论,我将代码更新为“如果”。我会在声明RuntimeErrorElement时出错(RuntimeError,第22行的错误:return self.age AttributeError:“Person”对象没有属性“age”
是的,这是因为您不总是设置self.age。您是否尝试过在我当前的评论中使用代码?@Mark Ah,这就是为什么我不喜欢只从评分程序调用代码的作业。请将您的get\u age代码更改为。)只需返回self.birthdate
,这将是错误的,但它将显示您获得的数据。
#TEST 1#
sara.get_name() returned Sara
inputs:
outputs:
----------
#TEST 2#
sara.get_height() returned 160
inputs:
outputs:
----------
#TEST 3#
sara.get_age() returned 20
inputs:
outputs:
----------
#TEST 4#
sara.get_description() returned Sara is 160 cm high and is 20 years old.
inputs:
outputs:
----------
#TEST 5#
eric.get_age() returned 10
inputs:
outputs:
----------
#TEST 6#
** ERROR **carter.get_age() returned 10
* EXPECTED * 11
inputs:
outputs:
----------
#TEST 7#
georgia.get_age() returned 14
inputs:
outputs:
def get_age(self):
birthdate = self.birthdate
today = date.today()
if today.month >= birthdate.month and today.day >= birthdate.day:
self.age = today.year - birthdate.year
else:
# haven't reached birthday yet
self.age = (today.year - birthdate.year) - 1
return self.age