[英]In Python, how do you use decimal module in a script rather than the interpreter?
I'm using Python 2.5.4 and trying to use the decimal module. 我正在使用Python 2.5.4并尝试使用十进制模块。 When I use it in the interpreter, I don't have a problem. 当我在翻译中使用它时,我没有问题。 For example, this works: 例如,这有效:
>>> 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? 这是怎么回事?
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. 您将脚本命名为decimal.py,因为脚本所在的目录是查找模块的路径中的第一个,您的脚本被找到并导入。 You don't have anything named Decimal in your module which causes this exception to be raised. 您的模块中没有任何名为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,bar.py,baz.py,spam.py或eggs.py这样的名字就是一个不错的选择。
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.