Pythonモジュール

| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |

例:

#単純なモジュール、calc.py


def add(x、y):

return (x + y)


def 減算(x、y):

return (x - y)

importステートメント
任意のPythonソースファイルをモジュールは、別のソースPythonファイルでimportステートメントを実行します。
インタプリタがimportステートメントを検出すると、モジュールが検索パスに存在する場合、モジュールをインポートします。検索パス—これは、インタプリタがモジュールをインポートするために探すディレクトリのリストです。たとえば、calc.pyモジュールをインポートするには、スクリプトの先頭に次のコマンドを配置する必要があります。


#calc。 pyインポーター

import calc

print add( 10 2

出力:

 12 

インポートからのステートメント

Python from ステートメントを使用すると、モジュールから特定の属性をインポートできます。 from .. import ..の構文は次のとおりです。


sqrt()とfactorial from
#math module

from math import sqrt、factorial


# 「mathをインポート」するだけの場合は、
#math. sqrt(16)およびmath.factorial()
#必須。

print sqrt 16

print factorial( 6

出力:

 4.0 720 

dir()関数
dir()が構築されました- in関数は、モジュールによって定義された名前を含む文字列のソートされたリストを返します。リストには、モジュールで定義されているすべてのモジュール、変数、関数の名前が含まれています。


#インラインモジュールをランダムにインポート

import ランダム

print dir (数学)

出力:

 [`BPF`、`LOG4`、 `NV_MAGICCONST`、`RECIP_BPF`、`Random`、`SG_MAGICCONST`、`SystemRandom`、`TWOPI`、`WichmannHill`、`_BuiltinMethodType`、`_MethodType`、`__all__`、`__builtins__`、`__doc_ `、` __name __`、` __package __`、` _acos`、` _ceil`、_e _cos`、`、` _exp`、` _hashlib`、` _hexlify`、` _inst`、` _log`、` _pi`、` _random `、` _sin`、` _ sqrt`、` _test`、` _test_generator`、` _urandom`、` _warn`、` betavariate`、` choice`、` Division`、` expovariate`、` gammavariate`、` gauss`、 `getrandbits `、` getstate`、` jumpahead`、` lognormvariate`、` normalvariate`、` paretovariate`、` randint`、` random`、` randrange`、` sample`、` seed`、` setstate`、` shuffle`、 `triangle`、`uniform`、`vonmisesvariate`、`weibullvariate`] 

組み込みのPythonモジュールを示すコードスニペット:

#組み込みの数学モジュールのインポート

import math


#二乗根関数( sqrt)を使用
#mathモジュール内

print math. sqrt 25


#pi関数を使用mathモジュールに含まれる

print math.pi


#2ラジアン= 11 4.59度

print math.degrees( 2


#60度=1.04ラジアン

print math.radians( 60


#Sine 2 radians

print math.sin( 2


#コサイン0.5ラジアン

print math.cos( 0.5


#0.23ラジアンタンジェント

print math.tan( 0.23


#1 * 2 * 3 * 4 = 24

print math.factorial( 4



#インラインモジュールをランダムにインポートします

import ランダム


#0から5までのランダムな整数を出力します

print random.randint( 0 5


#0から1までのランダムな浮動小数点数を出力します

print random.random()


#0〜100のランダムな数値

print random.random() * 100


リスト = [ 1 4 True 800 "python" 27 "hello" ]

< br> #ランダムモジュールのpick関数を使用して
#リストなどのセットからのランダムな要素

print random.choice( リスト


#インライン日時モジュールをインポート

インポート日時

from datetime import 日付

import 時間



#UnixEpoch1970年1月1日

print time.time()


#日付オブジェクトまでの秒数

pr int date.fromtimestamp( 454554

出力:

 5.0 3.14159265359 114.591559026 1.0471975512 0.909297426826 0.87758256189 0.234143362351 24 3 0.401533172951 88.4917616788 True 1461425771.87 1970-01-06 
amp-youtube data-videoid = nfYZL-uFm-c layout = response width = 665 height = 374>

この記事はGauravShresthaが残したものです。何か問題を見つけた場合、または上記のトピックに関する追加情報を共有したい場合は、コメントを投稿してください。 Python.Engineeringが好きで、貢献したい場合は、記事を書いて[email protected]にメールで送信することもできます。 Python.Engineeringホームページに表示される記事を参照して、他のオタクを助けてください。