module function class difference
Ex:The Python script game.py will implement the game. It will use the function draw_game from the file draw.py, or in other words, thedraw module, that implements the logic for drawing the game on the screen.
几种调用draw_game function的方法or调用draw module 中 draw_function 的方法
一:
# game.py
# import the draw module
import draw
def play_game():
...
def main():
result = play_game()
draw.draw_game(result)
# this means that if this script is executed, then
# main() will be executed
if __name__ == '__main__':
main()
–Import draw module and use the its function draw_game.
–In this module, using the dot operator to specify in which module the function is implemented.
二:
# game.py
# import the draw module
from draw import draw_game
def main():
result = play_game()
draw_game(result)
–We may also import the function draw_game directly into the main script’s namespace, by using the from command.
–The advantages of using this notation is that it is easier to use the functions inside the current module because you don’t need to specify which module the function comes from. However, any namespace cannot have two objects with the exact same name, so the import command may replace an existing object in the namespace.
三:
We may also use the import * command to import all objects from a specific module, like this:
# game.py
# import the draw module
from draw import *
def main():
result = play_game()
draw_game(result)
–This might be a bit risky as changes in the module might affect the module which imports it, but it is shorter and also does not require you to specify which objects you wish to import from the module.
Because any namespace cannot have two objects with the exact same name, import * may import some same name objets and make confusion.
四:
import foo.bar
from foo import bar
In the first method, we must use the foo prefix whenever we access the module bar. In the second method, we don’t, because we import the module to our module’s namespace.
If we create a directory called foo, which marks the package name, we can then create a module inside that package called bar. We also must not forget to add the init.py file inside the foo directory.