Importing functions from a module
Three ways to import functions:
1.
the simplest way: import everything from a module
advantage: simple usage e.g. of math functions
disadvantage: risk of naming conflicts when a variable has the same name as a module function
from numpy import *
print sin(pi/4)
# With this import method the following would give an error:
#sin = 5 # naming conflict!
#print sin(pi/4)
2.
import module under an alias name that is short enough to enhance code clarity
advantage: it is clear to see which function belongs to which module
import numpy as np
print np.sin(np.pi/4)
3.
import only the functions that are needed
advantage: simple usage e.g. of math functions
naming conflict possible, but less probable than with 1.
disadvantage: you must keep track of all the used functions and adapt the import statement if a
new function is used
from numpy import linspace, sin, exp, pi
print sin(pi/4)
Three ways to import functions:
1.
the simplest way: import everything from a module
advantage: simple usage e.g. of math functions
disadvantage: risk of naming conflicts when a variable has the same name as a module function
from numpy import *
print sin(pi/4)
# With this import method the following would give an error:
#sin = 5 # naming conflict!
#print sin(pi/4)
2.
import module under an alias name that is short enough to enhance code clarity
advantage: it is clear to see which function belongs to which module
import numpy as np
print np.sin(np.pi/4)
3.
import only the functions that are needed
advantage: simple usage e.g. of math functions
naming conflict possible, but less probable than with 1.
disadvantage: you must keep track of all the used functions and adapt the import statement if a
new function is used
from numpy import linspace, sin, exp, pi
print sin(pi/4)
No comments:
Post a Comment