简体   繁体   中英

What's the difference in: Import module & From module import module?

Here is my program that takes a list a words and sorts them from longest to shortest and breaks ties with the random module.

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

I get this error: TypeError: 'module' object is not callable

But when I do: from module import module It works?? Why is that?

from random import random 

is equivalent to

import random as _random
random = _random.random

so if you only do

import random

you have to use

random.random()

instead of

random()

random module has a random function. When you do import random you get the module, which obviously is not callable. When you do from random import random you get the function which is callable. That's why you don't see the error in the second case.

You can test this in your REPL.

>>> import random
>>> type(random)
module
>>> from random import random
>>> type(random)
builtin_function_or_method
from random import random

is equivalent to:

import random          # assigns the module random to a local variable
random = random.random # assigns the method random in the module random

You can't call the module itself, but you can call its method random . Module and method having the same name is only confusing to humans; the syntax makes it clear which one you mean.

When you invoke the command,

import random

You are importing a reference the module, which contains all the functions and classes. This reference is now in your namespace. The goodies inside the random module can now be accessed by random.func(arg1, arg2) .

This allows you to perform the following calls to the random module:

>>> random.uniform(1, 5)
2.3904247888685806
>>> random.random()
0.3249685500172673

So in your above code when the python interpreter hits the line,

t.append((len(word), random(), word))

The random is actually referring to the module name and throws an error because the module name isn't callable, unlike the function you're looking for which is inside.

If you were to instead invoke

from random import random

You are adding a reference in your name space to the function random within the module random . You could have easily have said from random import randint which would let you call randint(1, 5) without a problem.

I hope this explains things well.

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