简体   繁体   中英

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. 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:

NameError: name 'Decimal' is not defined

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'

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. You don't have anything named Decimal in your module which causes this exception to be raised.

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.

This works fine as is for me on 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') 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM