import module’s name
Basic form
1
2import mymath
print mymath.area(5)from module’s name import wanted object
- taking the wanted object from the module
- original object is lost if the name is using
- it can be used without the module’s name
1
2from mymath import area, mypi
print area(5)
from module’s name import *
- taking everything from the module without objects starting
__
1
2from mymath import *
print area(5)
- taking everything from the module without objects starting
import module’s name as another module name
- another name is used for calling the module
- It is recommended when the original name is too long or already used
1
2
3
4import string as chstr
print chstr
print
print chstr.punctuation
from module’s name import original name as another name[, name2 as another name2]
- another name is used for calling the module
1
2
3
4
5
6from string import replace as substitute[, upper as up]
print substitute
print substitute('ham chicken spam', 'chicke', 'egg')
print up
print up('abc')
- another name is used for calling the module
import
can be used anywhere(including in a function)
Compile and Load time
import mymath
works like this- Finding
mymath.pyc
- If that doesn’t exist, Finding
mymath.py
and creatingmymath.pyc
- Loading
mymath.pyc
into memory and executing
- Finding
.pyc
fileByte code file
- Kind of Object code not depending on machines or platform(OS)
- Python takes both executing ways of compile language and interpreter language
Deciding about creating new
.pyc
file- When modificatin time of
.py
is more recently than modification time of.pyc
- When modificatin time of
- Without
.py
file,import
is available with.pyc
- It can be use as the way to hide the original code
Using the same name again
- Though the name’s target is changed, the module remains in memory, if we
import
the module, that takes the module existing in memory. So, we can use the thing we defined additionally in the module at the code
Executing module and test code
__name__
- It is usually used for knowing if this module is used as the root module or in other module by
import
- Being used as the root module ->
__main__
Being used in other module -> that module’s name
1
2
3
4print __name__ # __main__ print
import prname
print prname.__name__ # prname printHow to use
1
2
3
4
5
6
7
8
9def add(a, b):
return a + b
def f():
print "Python is becoming popular."
if __name__ == "__main__":
print add(1, 10)
f()- Direct executing runs
if
statement - Being used in other module ignores
if
statement
- Direct executing runs
- It is usually used for knowing if this module is used as the root module or in other module by