Program to work out an age gives error about a getset_descriptor?

梦想的初衷 提交于 2020-12-12 05:08:14

问题


I am trying to write a very simple Python program to work out someone's age and I think, in theory, it should work however every time I try to run it, it throws this error:

What year were you born in? 2005
Traceback (most recent call last):
  File "python", line 5, in <module>
TypeError: unsupported operand type(s) for -: 'getset_descriptor' and 'int'

I have tried turning datetime.year and (year) (same things) in to integers. It worked but didn't make a difference as the both are already integers. This is my code:

from datetime import datetime
year = datetime.year
born = input("What year were you born in?")
born = int(born)
end = year - born
print(end)

回答1:


year = datetime.year does not give you the current year. It gives you an unbound descriptor object instead (the getset_descriptor in your error):

>>> datetime.year
<attribute 'year' of 'datetime.date' objects>
>>> type(datetime.year)
<class 'getset_descriptor'>
>>> datetime.year - 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'getset_descriptor' and 'int'

Don't worry too much about the exact type of object here, that's just an implementation detail needed to make instances of a built-in immutable type like datetime work. It just means you don't have an instance of the datetime type, so there is no year value for that instance either.

If you want the current year, use datetime.now().year:

year = datetime.now().year

datetime.now() gives you a datetime instance, the one representing the current time and date. That instance has a valid year attribute.

You could also use datetime.date.today() of course:

>>> from datetime import datetime, date
>>> datetime.now()
datetime.datetime(2016, 12, 31, 14, 58, 14, 994030)
>>> datetime.now().year
2016
>>> date.today().year
2016


来源:https://stackoverflow.com/questions/41409301/program-to-work-out-an-age-gives-error-about-a-getset-descriptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!