关于 python 命名空间的快速问题。我是Python新手,所以这可能是一个新手问题,并且有一个简单的答案,但我已经搜索过,似乎找不到它。
我的问题只是想知道是否有一种方法可以声明命名空间,这样您就不需要每次访问其中声明的类时都说出模块名称。 例如:
>>> import fractions
>>> myFrac = fractions.Fraction("3/4")
>>> str(myFrac)
'3/4'
>>> myFrac = Fraction("3/4")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Fraction' is not defined
>>>
我想知道是否有办法避免输入模块名称。我也感兴趣的是这样做是否是用 python 编写代码的惯例。
最佳答案
您可以使用from <module> import <class>
缩短您的工作
from fractions import Fraction
编辑: 由于这个问题是关于命名空间的,因此您还可以提供更漂亮的名称
from animals import Dog as Scooby
然后使用模块名称 Scooby。尽管这使得以后很难跟踪模块的使用情况。
关于Python 3 假设模块命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35320327/