例:
#単純なモジュール、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関数は、モジュールによって定義された名前を含む文字列のソートされたリストを返します。リストには、モジュールで定義されているすべてのモジュール、変数、関数の名前が含まれています。
出力: [`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モジュールを示すコードスニペット:
< br>
出力: 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-06amp-youtube data-videoid = nfYZL-uFm-c layout = response width = 665 height = 374> この記事はGauravShresthaが残したものです。何か問題を見つけた場合、または上記のトピックに関する追加情報を共有したい場合は、コメントを投稿してください。 Python.Engineeringが好きで、貢献したい場合は、記事を書いて[email protected]にメールで送信することもできます。 Python.Engineeringホームページに表示される記事を参照して、他のオタクを助けてください。 |