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 followi开发者_StackOverflow中文版ng 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:))
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
.
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.
If you use 'from moduleName import ....' then you get all classes, functions and variables that you specified after import or all if you specify *.:
from random import *
for i in range(15):
print randrange(3,13,3)
But note that this is not very good to import all, it would be better to import only required classes, functions and variables so in case you need only randrange you need to use:
from random import randrange
for i in range(15):
print randrange(3,13,3)
In case you are using import random this means that you importing module so you need to specify moduleName. when you want to use it so:
import random
for i in range(15):
print random.randrange(3,13,3)
from random import *
imports all functions from a module called random, but not random
itself.
Here you can directly call the functions in random as follows: randrange(3,13,3)
, etc
import random
imports the name random, from which you can later call functions as follows: random.randrange(3,13,3)
, etc
精彩评论