Many of us wonders what is the difference between import os (for example) and from os import getcwd.
It's simple, each python module has a table of names ,
What import command does it simply importing names that you tell it to import.
What do you mean by names ?
A name in a module is anything inside it with a name : internal functions, constants , ... etc
Example : os module
The os module has functions like :
- getcwd() : returns the name of the current working directory.
- chdir(path) : changes the current working directory.
- getuid() : returns the id of the current user of this process.
- and many more other functions.
- name (os.name) : the name of the os.
When to use import xxx ?
Consider you need to know the path of the current working directory, so you have to call the function getcwd() from the os module.
if you used import os , you have to write os.getcwd() , you have to write the module name before the function name.
from os import getcwd()
this enables you to use getcwd() function without prefixing it with the module name.
so from os import * makes you able to use all names inside the os module without prefixing any of them with the module name , because the entire name table of the os module is imported , not only getcwd name as the previous example.
0 comments:
Post a Comment