Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between FROM random IMPORT* and IMPORT random? (random() and randrange())

Tags:

python

import

In the book has been this codesample:

from random import*
for i in range(15):                     
        print random.randrange(3,13,3)

And it have got result in the book.

But when I run it in the Netbeans. The following excaption arosed:

*

Traceback (most recent call last): File "C:\Users\Lacces\Documents\NetBeansProjects\Python_GS_Tanuljunk_meg_programozni\src\Adatszerkezetek\Lista.py", line 11, in print random.randrange(3,13,3) #3-tól 13-ig, 3 érték elválasztásal AttributeError: 'builtin_function_or_method' object has no attribute 'randrange'

*

I have call to help the google, and I found this for the import:

import random

With that I used this instead of from random import*

And it worked! No exception!

Can somebody explain to me why throw exception at the first time, and why not at the second time (for a beginner programmer:))

like image 690
blaces Avatar asked Dec 09 '22 07:12

blaces


2 Answers

When you from random import *, all the definitions from random become part of the current name space. This means you don't have to prefix anything with random., but it also means you may get a name collision without even knowing it.

The preferred way is import random.

like image 110
Mark Ransom Avatar answered Dec 11 '22 19:12

Mark Ransom


Importing everything from a module is discouraged just because of these surprising side effects: The module random contains a function random, so import * from random does the following:

from random import randrange
from random import random
...

Now, when you're accessing random, you're accessing the function instead of the module. You could use randrange (without the prefix random.), but import random and explicitly stating what module a function is from is the better idea.

like image 22
phihag Avatar answered Dec 11 '22 21:12

phihag