A function or class once created is divided into files for reuse.
Each .py
file is called module or library.
In Python, the module name is the part of the file name without the extension.
By importing each .py
file, it is possible to use the functions and classes in the module.
Here's the most basic import method.
test.py
class AAA:
def __init__(self, a):
self.a = a
def get_a(self):
return self.a
def add_a(self):
self.a += 1
main.py
# import "Module name"
import test
#Functions of the imported module(Method)And when using classes
A = test.AAA(1) #Module name.Class name or function name
A.add_a() #instance.Method name
b = A.get_a # b=2
By giving a name, you can omit long module names.
Example) import pandas as pd
import numpy as np
main.py
# import "Module name" as "The name you want to give"
import test as t
A = t.AAA(1) #Name given.Class name or function name
A.add_a() #instance.Method name
b = A.get_a # b=2
Since the notation of the module name can be omitted, it is done in the class that is frequently used.
Example) from keras.layers import Conv2D
from PIL import Image, ImageDraw
main.py
# from "Module name" import "Class name or function name"
from test import AAA
A = AAA(1) #Class name or function name
Easy to import in large quantities from modules. All functions and classes in the module are imported.
Example) from PIL import *
main.py
# from "Module name" import *
from test import *
A = AAA(1) #Class name or function name
A directory containing multiple modules is called package.
main.py
# ~~~Directory structure~~~
#Current directory-src-test.py
# └main.py
# import "package name.Module name"
import src.test
A = src.test.AAA(1) #package name.Module name.Class name or function name
# or
# from "package name" import "Module name"
from src import test
A = test.AAA(1) #Module name.Class name or function name
The one who seems to use it often
Module name | Overview |
---|---|
os | OS related |
os.path | Path related |
sys | Python runtime environment |
io | Input / output |
datetime | Date and time |
calendar | calendar |
time | time |
re | Regular expression |
math | Math |
random | random number |
statistics | statistics |
json | json |
csv | csv |
sqlite3 | SQLite |
zipfile | zip file |
tarfile | tar file |
html | HTML |
html.paser | HTML analysis |
http | HTTP |
urllib | URL |
urllib.request | URL request |
socket | socket |
Recommended Posts