从类中的对象导入函数的语法(Python2)

2024-04-26 04:25:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够直接访问strtime函数(无datetime.datetime.strptime()datetime.strptime()

我可以做到:

from datetime import datetime
strptime = datetime.strptime

但有没有办法在进口线上完成同样的事情呢?你知道吗

另外,你能在一行做多个项目吗?你知道吗

下面是我真正想做的伪代码:

from datetime.datetime import strftime, strptime

Datetime只是一个例子,类似的事情对于在其他库中导入类方法也很有用。你知道吗


Tags: 项目方法函数代码fromimportdatetime事情
2条回答

这些是datetime类型的方法,不能直接导入。不能直接导入模块顶级命名空间下的任何内容。从the documentation

The from form does not bind the module name: it goes through the list of identifiers, looks each one of them up in the module found in step (1) [i.e., the module being imported], and binds the name in the local namespace to the object thus found.

也就是说,导入的名称必须是模块命名空间中的名称。它们的嵌套再深不过了。因此,您不能像您显然想做的那样,只导入模块中类的某些方法。你知道吗

“我能在进口线上做这个吗?”不是

参见definition of the import statement in Python 2。语句从模块中导入内容。在datetime模块中有一个datetime类。你能做的就是

from datetime import datetime

你已经很清楚这是做什么的,因为你在你的问题中完美地使用了它。看起来你想这么做

from datetime import datetime.strptime

但这是一个语法错误,因为datetime.strptime不是标识符。你知道吗

你不能说

from datetime.datetime import strptime

或者是因为Python将查找名为datetime.datetime模块。你知道吗

import语句不能按您希望的方式工作。你知道吗

注意,datetime模块的作者选择使strptime成为类方法(使用@classmethod),而不是函数。因此,如果您想在不使用类限定符的情况下使用strptime,则必须执行所做的操作,即赋值给名为strptime的变量。你知道吗

相关问题 更多 >