I'm using Python 2.5.4 and trying to use the decimal module. When I use it in the interpreter, I don't have a problem. For example, this works:
我正在使用Python 2.5.4并尝试使用decimal模块。当我在解释器中使用它时,我没有问题。例如,这个工作原理:
>>> from decimal import *
>>> Decimal('1.2')+ Decimal('2.3')
Decimal("3.5")
But, when I put the following code:
但是,当我输入以下代码时:
from decimal import *
print Decimal('1.2')+Decimal('2.3')
in a separate file (called decimal.py) and run it as a module, the interpreter complains:
在一个单独的文件(称为decimal.py)中作为模块运行,解释器会抱怨:
NameError: name 'Decimal' is not defined
NameError:不定义“Decimal”
I also tried putting this code in a separate file:
我也尝试把这些代码放在一个单独的文件中:
import decimal
print decimal.Decimal('1.2')+decimal.Decimal('2.3')
When I run it as a module, the interpreter says:
当我作为一个模块运行时,解释器会说:
AttributeError: 'module' object has no attribute 'Decimal'
AttributeError: 'module'对象没有属性'Decimal'
What's going on?
这是怎么呢
2 个解决方案
#1
17
You named your script decimal.py, as the directory the script is in is the first in the path the modules are looked up your script is found and imported. You don't have anything named Decimal in your module which causes this exception to be raised.
您将脚本命名为decimal。py,因为脚本所在的目录是路径中的第一个,所以查找模块并导入脚本。在你的模块中没有任何命名为Decimal的东西,这会引起这个异常。
To solve this problem simply rename the script, as long as you are just playing around something like foo.py, bar.py, baz.py, spam.py or eggs.py is a good choice for a name.
要解决这个问题,只需重命名脚本,只要您只是在玩foo之类的东西。py,酒吧。py,巴兹。py,垃圾邮件。py或鸡蛋。py是一个很好的名字选择。
#2
3
This works fine as is for me on Python 2.5.2
这和我在Python 2.5.2中使用的一样好
from decimal import *
print Decimal('1.2')+Decimal('2.3')
I would encourage you to specify what you want to use from decimal
我鼓励您指定要使用的十进制
from decimal import Decimal
print Decimal('1.2')+Decimal('2.3')
In your other example you should use
在您的另一个示例中,您应该使用
import decimal
print decimal.Decimal('1.2')+decimal.Decimal('2.3')
#1
17
You named your script decimal.py, as the directory the script is in is the first in the path the modules are looked up your script is found and imported. You don't have anything named Decimal in your module which causes this exception to be raised.
您将脚本命名为decimal。py,因为脚本所在的目录是路径中的第一个,所以查找模块并导入脚本。在你的模块中没有任何命名为Decimal的东西,这会引起这个异常。
To solve this problem simply rename the script, as long as you are just playing around something like foo.py, bar.py, baz.py, spam.py or eggs.py is a good choice for a name.
要解决这个问题,只需重命名脚本,只要您只是在玩foo之类的东西。py,酒吧。py,巴兹。py,垃圾邮件。py或鸡蛋。py是一个很好的名字选择。
#2
3
This works fine as is for me on Python 2.5.2
这和我在Python 2.5.2中使用的一样好
from decimal import *
print Decimal('1.2')+Decimal('2.3')
I would encourage you to specify what you want to use from decimal
我鼓励您指定要使用的十进制
from decimal import Decimal
print Decimal('1.2')+Decimal('2.3')
In your other example you should use
在您的另一个示例中,您应该使用
import decimal
print decimal.Decimal('1.2')+decimal.Decimal('2.3')