python modules
1930 ワード
module function A module is a collection of functions and variables that have been bundled together in a single file. Modules help us: Organize our code by separating related functions and objects into their own modules. Gain new functionality by using code written by others without spending a large amount of time diving into how exactly it's implemented. Modules are usually organized around a theme. Some modules have long names, however, and this means that we need to use the full module name each time we want to use any of the objects within that module. Instead, we can assign an alias when we import the module: If a module contains hundreds of functions and we only need a few, specific functions, we can import just the ones we need:
4 Lastly, we can import all of the objects (this includes both objects and functions) from a module into the global namespace using the * symbol:
This is generally considered not good practice, because your namespace becomes polluted with all of these named references to objects you may not be using. In addition, if you're working with multiple modules, you run into the danger of overwriting some of the names in the namespace.
module variables
So far, we've only worked with the functions defined within modules. Now, let's explore how to use the variables defined within modules. We access a module's variables with dot notation, just like we do with functions.
import my_module as m
m.function1()
m.function2()
from my_module import function1
from my_module import function1, function2
4 Lastly, we can import all of the objects (this includes both objects and functions) from a module into the global namespace using the * symbol:
from my_module import *
This is generally considered not good practice, because your namespace becomes polluted with all of these named references to objects you may not be using. In addition, if you're working with multiple modules, you run into the danger of overwriting some of the names in the namespace.
module variables
So far, we've only worked with the functions defined within modules. Now, let's explore how to use the variables defined within modules. We access a module's variables with dot notation, just like we do with functions.
import my_module
print(my_module.some_values)
import math
print(math.pi)
a = math.sqrt(math.pi)
b = math.ceil(math.pi)
c = math.floor(math.pi)