Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.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变量和函数注释引发AttributeError_Python_Python 3.x - Fatal编程技术网

Python变量和函数注释引发AttributeError

Python变量和函数注释引发AttributeError,python,python-3.x,Python,Python 3.x,虽然variablecurrent\u timestamp(以及函数返回值)和variabletime是datetime.datetime类对象,但下面的代码引发了AttributeError:type对象“datetime.datetime”没有属性“datetime” from datetime import datetime def current_time() -> datetime.datetime: current_timestamp: datetime.da

虽然variable
current\u timestamp
(以及函数返回值)和variable
time
datetime.datetime
类对象,但下面的代码引发了
AttributeError:type对象“datetime.datetime”没有属性“datetime”

from datetime import datetime

def current_time() -> datetime.datetime:
   
    current_timestamp: datetime.datetime = datetime.now()
    return current_timestamp

time: datetime.datetime = current_time()
print(time)
仅更改函数返回值和
time
变量的注释即可解决此问题

from datetime import datetime

def current_time() -> datetime:
   
    current_timestamp: datetime.datetime = datetime.now()
    return current_timestamp

time: datetime = current_time()
print(time)
有人能解释为什么注释
datetime.datetime
只为函数返回值和
time
变量引发AttributeError,而不为
当前时间戳
变量引发AttributeError吗


我正在运行Python 3.8。

答案只在于您的实现

从datetime导入datetime对象时,您希望函数从datetime模块返回datetime类型的对象

datetime模块下有许多类,其中一个是datetime

导入日期时间
def current_time()->datetime.datetime:
当前时间戳:datetime=datetime.datetime.now()
返回当前时间戳
时间:datetime.datetime=当前时间()
打印(时间)
From,其中定义了此语法

注释局部变量将导致解释器将其视为局部变量,即使它从未被赋值。将不计算局部变量的注释:

def f():
    x: NonexistentName  # No error.
x: NonexistentName  # Error!
class X:
    var: NonexistentName  # Error!
但是,如果处于模块或类级别,则将对类型进行评估:

def f():
    x: NonexistentName  # No error.
x: NonexistentName  # Error!
class X:
    var: NonexistentName  # Error!
此外,在模块或类级别,如果要注释的项是一个简单的名称,那么它和注释将作为从名称到已评估注释的有序映射存储在该模块或类的
\uuuuuuuuuuuuuuuuuuuuu
属性中

因此,原因是注释是一种通用工具,允许将注释用于类型签名以外的其他用途。在模块或类级别,您可以使用反射技术在运行时访问此信息,因此该值必须存在并将被计算。但是,当应用于局部变量时,局部变量上没有反射,因此注释仅对解析代码的第三方工具有用,因此Python本身没有理由对其进行计算


值得注意的是,在第二个示例中,
mypy
将失败,如果您想使用实际的类型检查器,您必须在每个地方更正注释。

我非常确定,他询问的内容是由Python本身指定的。无论如何,我也可以在自己的Python3.7上可靠地重现结果,所以我怀疑这完全是实现的一个怪癖。啊。。!!明白了,我一开始就误解了这个问题。你的解释帮助我理解了。尽管注意到,行为正在改变。如果使用来自未来导入注释的
,则不会计算所有注释,并将其保留为字符串。我相信这将成为Python 3.10中的默认行为。我目前使用的代码库依赖于以前的行为,更新它不会很有趣。