0
0

Python学習9日~モジュール~

Posted at

モジュール

プログラムを構成する部品のこと
Pythonでは作成したファイル(.pyファイル)のこと

パッケージ

モジュールを詰め合わせたもの

ライブラリ

組み込みではない(Python処理系に内蔵されていない)機能

random

擬似乱数に関するモジュール

import random
random.randint(1,10)
実行結果
4

randint関数は指定した範囲でランダムに整数を生成してくれる関数

import random as r

モジュールに任意の名前をつけることができる
上記例ではrandomモジュールをrとしてimportしている

from節

モジュール名なしで機能を使えるようにする

# 特定のモジュールだけを使えるようにする
from モジュール名 import 機能名,...

# モジュール内すべての機能を使えるようにする
from モジュール名 import *

# インポートした機能に別名をつける
# from モジュール名 import 機能名 as 別名
example.py
from random import randint as ri
ri(1,10)
実行結果
3

モジュールがパッケージ名を伴う場合にはfrom節付きのimport文を使って、パッケージ名だけを省略したり、パッケージ名、モジュール名の両方を省略することができる

example.py
# パッケージ名を省略してモジュールを使えるようにする
from urllib import parse
print(parse.urlparse('https//:www.python.org/'))

# パッケージ名とモジュール名を省略して機能を使えるようにする
from urllib.parse import urlparse
print(urlparse('https//:www.python.org/'))
実行結果
ParseResult(scheme='', netloc='', path='https//:www.python.org/', params='', query='', fragment='')
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0