這是我的程序,它將一個單詞列表並將它們從最長到最短排序,並打破與隨機模塊的關係。有什麼區別:導入模塊和從模塊導入模塊?
import random
def sort_by_length1(words):
t = []
for word in words:
t.append((len(word), random(), word))
t.sort(reverse = True)
res = []
for length, randomm, word in t:
res.append(word)
return res
我得到這個錯誤:類型錯誤:「模塊」對象不是可調用
但是當我做:from module import module
它的工作原理?這是爲什麼?
import random # assigns the module random to a local variable
random = random.random # assigns the method random in the module random
您不能調用模塊本身,但你可以調用它的方法random:
那麼,爲什麼不只是導入隨機工作?我對這種語言相當陌生,所以我在理解這個意思時有點困難。 –
@ G.G由於'import random'允許您在'random'名稱下訪問導入的*模塊*。你不能調用一個模塊。 – phihag
模塊與函數完全不同。這只是一個巧合,在這種情況下,它們都有相同的名稱。 – patrys