[英]Why do I get a TypeError: 'module' object is not callable when trying to import the random module?
I am using Python 2.6 and am trying to run a simple random number generator program (random.py): 我正在使用Python 2.6,我正在尝试运行一个简单的随机数生成器程序(random.py):
import random
for i in range(5):
# random float: 0.0 <= number < 1.0
print random.random(),
# random float: 10 <= number < 20
print random.uniform(10, 20),
# random integer: 100 <= number <= 1000
print random.randint(100, 1000),
# random integer: even numbers in 100 <= number < 1000
print random.randrange(100, 1000, 2)
I'm now receiving the following error: 我现在收到以下错误:
C:\Users\Developer\Documents\PythonDemo>python random.py
Traceback (most recent call last):
File "random.py", line 3, in <module>
import random
File "C:\Users\Developer\Documents\PythonDemo\random.py", line 8, in <module>
print random.random(),
TypeError: 'module' object is not callable
C:\Users\Developer\Documents\PythonDemo>
I've looked at the Python docs and this version of Python supports random. 我查看了Python文档,这个版本的Python支持随机。 Is there something else I'm missing? 还有什么我想念的吗?
Name your file something else. 将文件命名为其他内容。 In Python a script is a module, whose name is determined by the filename. 在Python中,脚本是一个模块,其名称由文件名决定。 So when you start out your file random.py
with import random
you are creating a loop in the module structure. 因此,当您使用import random
开始文件random.py
,您将在模块结构中创建一个循环。
Rename your sample program file to myrandom.py or something. 将示例程序文件重命名为myrandom.py或其他内容。 You are confusing import I would bet. 你打赌我很困惑。
Edit : Looks like you have same name with built-in random module, so you should change filename to something else as others suggested 编辑 :看起来你有相同的内置随机模块的名称,所以你应该像其他人建议的那样将文件名更改为其他内容
but after that, you still need to change your codes to initiate Random class 但在此之后,您仍需要更改代码以启动Random类
rand=random.Random()
rand.uniform(10, 20)
and also for others because you are calling module itself, instead of Random class 还有其他因为你正在调用模块本身而不是Random类
>>> for i in range(5):
... # random float: 0.0 <= number < 1.0
... print rand.random(),
...
... # random float: 10 <= number < 20
... print rand.uniform(10, 20),
...
... # random integer: 100 <= number <= 1000
... print rand.randint(100, 1000),
...
... # random integer: even numbers in 100 <= number < 1000
... print rand.randrange(100, 1000, 2)
...
0.024357795662 12.3296648076 886 478
0.698607283236 16.7373296747 245 638
0.69796131038 14.739388574 888 482
0.543171786714 11.3463795339 106 744
0.752849564435 19.4115177118 998 780
>>>
You script is importing itself since it is named random.py
and then trying to call itself as a method. 您的脚本正在导入自身,因为它名为random.py
,然后尝试将自身称为方法。 Rename your script to something else (like test.py
) and it will work. 将您的脚本重命名为其他内容(如test.py
),它将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.