Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算年龄的程序给出了关于getset_描述符的错误?_Python_Python 3.x_Datetime_Integer_Typeerror - Fatal编程技术网

Python 计算年龄的程序给出了关于getset_描述符的错误?

Python 计算年龄的程序给出了关于getset_描述符的错误?,python,python-3.x,datetime,integer,typeerror,Python,Python 3.x,Datetime,Integer,Typeerror,我正在尝试编写一个非常简单的Python程序来计算某人的年龄,我认为,理论上,它应该可以工作,但是每次我尝试运行它时,它都会抛出以下错误: 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

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

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'

year=datetime.year
不提供当前年份。它将为您提供一个未绑定的描述符(错误中的
getset\u描述符
):

为您提供一个
datetime
实例,该实例表示当前时间和日期。该实例具有有效的
year
属性

当然,您也可以使用:

>>> 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\u描述符?我很喜欢你的回答,不过,只有一些部分我不明白。@Kiran:它是C中定义的一些Python内置类型上的一个内部对象,这些对象在实例上没有
\u dict\u
属性。换句话说,您通常不需要担心的专业实现细节。
>>> 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'
year = datetime.now().year
>>> from datetime import datetime, date
>>> datetime.now()
datetime.datetime(2016, 12, 31, 14, 58, 14, 994030)
>>> datetime.now().year
2016
>>> date.today().year
2016