我可以在python中将变量命名为“ now”吗?

这似乎是一个幼稚的问题,但到目前为止,我在网络上没有找到任何答案,并且我不想在我的代码中引起任何不一致的行为。

我可以now在python代码中命名变量吗?有一个名为的功能now(),这就是为什么我对此表示怀疑的原因。

例子:

now = datetime.datetime.now()

可以将其视为存储返回值的任何普通变量datetime.datetime.now()吗?还是在任何时候都有不同的表现?


翻过高山走不出你
浏览 192回答 3
3回答

RISEBY

now 不是python中的关键字,因此您可以将其用作变量名。有可能干扰datetime.datetime.now()吗?不。详细说明:也没有命名为now()的函数;它与datetime对象相关联(这是一个类方法),您将始终需要datetime.now()使用它。因此,它始终与名为的变量区分开now。仅当您按以下方式分配时:now = datetime.datetime.now在这里,名为的新变量now等于datetime.now() 函数(而不是函数的结果)。但是在这种情况下,您要对此工作完全负责。即使那样,更改now为其他内容也不会更改datetime.now。使用,但是now = datetime.datetime.now()将函数调用的结果分配给变量now(而不是函数本身),并且该函数保持原样。值得注意的是,是否应该覆盖内置函数。这是Python 3.7中的内置函数的列表。您可以为每个名称分配一个值,但实际上您会失去该功能*,以后可能会遇到麻烦。例如:str = "Hello there"a = 123<more code>value = str(a)&nbsp; # causes a TypeError, because we re-assigned str因此,请尽量避免这种情况(这list = [1,2,3]是应该避免的另一个常见错误)。但now()不是内置函数,如上所述。*即使重新分配后,也有一些方法可以检索原始的内置函数,但这不在本主题的讨论范围之内。

慕容3067478

以下是python中使用的关键字,此外,您还可以使用所需的任何关键字False&nbsp; &nbsp; &nbsp; await&nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp;import&nbsp; &nbsp; &nbsp;passNone&nbsp; &nbsp; &nbsp; &nbsp;break&nbsp; &nbsp; &nbsp; except&nbsp; &nbsp; &nbsp;in&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;raiseTrue&nbsp; &nbsp; &nbsp; &nbsp;class&nbsp; &nbsp; &nbsp; finally&nbsp; &nbsp; is&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;returnand&nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp;for&nbsp; &nbsp; &nbsp; &nbsp; lambda&nbsp; &nbsp; &nbsp;tryas&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;def&nbsp; &nbsp; &nbsp; &nbsp; from&nbsp; &nbsp; &nbsp; &nbsp;nonlocal&nbsp; &nbsp;whileassert&nbsp; &nbsp; &nbsp;del&nbsp; &nbsp; &nbsp; &nbsp; global&nbsp; &nbsp; &nbsp;not&nbsp; &nbsp; &nbsp; &nbsp; withasync&nbsp; &nbsp; &nbsp; elif&nbsp; &nbsp; &nbsp; &nbsp;if&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;or&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;yield我希望回答你的问题

摇曳的蔷薇

import this 说命名空间是一个很棒的主意-让我们做更多这些吧!now即使有一个调用的函数,您也可以将其用作变量,datetime.datetime.now()因为该函数位于另一个名称空间中。每个模块(例如module datetime)都是一个名称空间,并且该模块(例如datetime.datetime)中的每个类或类型都是一个单独的名称空间。即使在函数内部,您也可以创建一个与周围代码中定义的名称相同的局部变量:a = 1def f(x):&nbsp; &nbsp; a = x + 2&nbsp; &nbsp; print (a)f(4)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # prints 6print (a)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# prints 1尽管这样做可能会使您的代码读者(包括您自己)感到困惑。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python