本文介绍了确定年龄的程序会给出有关getset_descriptor的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个非常简单的Python程序来计算某人的年龄,我认为,从理论上讲,它应该可以工作,但是每次我尝试运行它时,它都会引发此错误:

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'

我尝试将datetime.year(year)(相同)转换为整数.它可以工作,但没有区别,因为两者都已经是整数.这是我的代码:

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)

推荐答案

year = datetime.year没有给您当前年份.它为您提供了一个未绑定的描述符对象(错误中的getset_descriptor) :

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'

这里不必太担心对象的确切类型,这只是使像datetime这样的内置不可变类型的实例工作所需的实现细节.这只是意味着您没有datetime类型的 instance ,因此该实例也没有year值.

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.

如果需要当前年份,请使用datetime.now().year:

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

year = datetime.now().year

datetime.now() 为您提供了 instance ,代表当前时间和日期.该实例具有有效的year属性.

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

您还可以使用 datetime.date.today() 课程:

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

这篇关于确定年龄的程序会给出有关getset_descriptor的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 20:09