在Python中,如何在脚本而不是解释器中使用十进制模块?

jac*_*ack 10 python decimal

我正在使用Python 2.5.4并尝试使用十进制模块.当我在翻译中使用它时,我没有问题.例如,这有效:

>>> from decimal import *
>>> Decimal('1.2')+ Decimal('2.3')
Decimal("3.5")
Run Code Online (Sandbox Code Playgroud)

但是,当我把以下代码:

from decimal import *
print Decimal('1.2')+Decimal('2.3')
Run Code Online (Sandbox Code Playgroud)

在一个单独的文件(称为decimal.py)并将其作为模块运行,解释器抱怨:

NameError:未定义名称"Decimal"

我也尝试将此代码放在一个单独的文件中:

import decimal
print decimal.Decimal('1.2')+decimal.Decimal('2.3') 
Run Code Online (Sandbox Code Playgroud)

当我将其作为模块运行时,解释器说:

AttributeError:'module'对象没有属性'Decimal'

这是怎么回事?

Das*_*Ich 18

您将脚本命名为decimal.py,因为脚本所在的目录是查找模块的路径中的第一个,您的脚本被找到并导入.您的模块中没有任何名为Decimal的内容会导致引发此异常.

要解决这个问题,只需重命名脚本,只要您只是玩foo.py,bar.py,baz.py,spam.py或eggs.py这样的名字就是一个不错的选择.


Joh*_*ooy 5

这对我来说在Python 2.5.2上工作正常

from decimal import *
print Decimal('1.2')+Decimal('2.3')
Run Code Online (Sandbox Code Playgroud)

我鼓励您从十进制指定要使用的内容

from decimal import Decimal
print Decimal('1.2')+Decimal('2.3')
Run Code Online (Sandbox Code Playgroud)

在另一个示例中,您应该使用

import decimal
print decimal.Decimal('1.2')+decimal.Decimal('2.3') 
Run Code Online (Sandbox Code Playgroud)