Chapter3 (Part 3)
Chapter3 (Part 3)
OBJECT-ORIENTED PYTHON
3.1 USE FUNCTION IN PYTHON (PART 3)
Learning Outcome:
•Define Function
•Define Call Function
•Import and Use Module √
Import and Use Module
Define Python Modules
• Python module is a piece of code.
• Exiting the interpreter destroys all functions and variables we
created. But when we want a longer program, we create a script.
• With Python, we can put such definitions in a file, and use them
in a script, or in an interactive instance of the interpreter. Such a
file is a module.
• A module is a file that contains Python statements and
definitions. A Python modules looks like this:
Example : calc.py
How to Create Python Modules?
To create a module just save the code you want in a file with
the file extension .py:
Example:
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import
statement:
Example:
Import the module named mymodule, and call the greeting
function:
import mymodule
mymodule.greeting("Jonathan")
Example:
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Variables in Module
Example:
Import the module named mymodule, and access the
person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Output : 36
Re-naming a Module
• Can create an alias when you import a module, by using the
as keyword:
Example:
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
Import From Module
• Can choose to import only parts from a module, by using the
from keyword.
Example:
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Import From Module
Example:
Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])
Note: When importing using the from keyword, do not use the
module name when referring to elements in the module. Example:
person1["age"], not mymodule.person1["age"]
END