簡體   English   中英

為什么我會得到一個TypeError:'module'對象在嘗試導入隨機模塊時是不可調用的?

[英]Why do I get a TypeError: 'module' object is not callable when trying to import the random module?

我正在使用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)

我現在收到以下錯誤:

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>

我查看了Python文檔,這個版本的Python支持隨機。 還有什么我想念的嗎?

將文件命名為其他內容。 在Python中,腳本一個模塊,其名稱由文件名決定。 因此,當您使用import random開始文件random.py ,您將在模塊結構中創建一個循環。

將示例程序文件重命名為myrandom.py或其他內容。 你打賭我很困惑。

編輯 :看起來你有相同的內置隨機模塊的名稱,所以你應該像其他人建議的那樣將文件名更改為其他內容

但在此之后,您仍需要更改代碼以啟動Random類

rand=random.Random()

rand.uniform(10, 20)

還有其他因為你正在調用模塊本身而不是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
>>>

您的腳本正在導入自身,因為它名為random.py ,然后嘗試將自身稱為方法。 將您的腳本重命名為其他內容(如test.py ),它將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM