- 追加された行はこの色です。
- 削除された行はこの色です。
#author("2018-11-06T13:58:46+00:00","","")
* Python - オブジェクト指向スクリプト言語 [#ibc1c66a]
#author("2019-01-13T07:49:50+00:00","","")
* Pythonの基礎 [#y618fbfd]
#setlinebreak(on);
#contents
-- 関連
--- [[Python覚え書き]]
--- [[Pythonのインストール]]
--- [[Python のパッケージング]]
--- [[Pythonのデコレータ]]
--- [[PythonでAWS DynamoDBのCRUDを書いてみる]]
--- [[Pythonのstrptimeが遅い]]
--- [[Pythonのチューニング]]
--- [[Pythonのパフォーマンス確認]]
--- [[FizzBuzzで頭の体操]]
--- [[pytest入門]]
--- [[OpenSSLで電子署名の生成と署名検証]]
--- [[pythonでWebサーバを書いてみる]]
--- [[Flaskの基礎]]
--- [[Djangoの基礎]]
--- [[pandas入門]]
--- [[PyTorch入門]]
--- [[TensorFlow入門]]
** 文字の利用 [#g5d33724]
#mycode2(){{
# 文字変数の宣言
strval="string"
strval='string'
# 文字列の連結
strval = 'str' + 'ring' # string
strval = 'str' 'ring' # string
# 文字列の反復
strval = "string"
strval2 = strval*2 # stringstring
# 文字列の添字表記
strval1[0] #'T'
strval1[0:2] #'TE'
}}
** 数値の利用 [#i1f8efe6]
#mycode2(){{
# 数値変数の宣言
intval=100
# 整数の除算は floor (実数の解を越えない最大の整数) を返す:
intval = 7/3 ※2
}}
** リストの利用 [#x4c8a947]
#mycode2(){{
# リスト変数の定義
a = ['str1', "str2", 100, 1234]
a[0] #str1
a[1] #str2
# リスト内容の置換
a = ['str1', "str2", 100, 1234]
a[0:2] = [111, 222] # a = [111,222,100,123]
# リスト数の取得
a = ['str1', "str2", 100, 1234]
len(a) #4
}}
** if文 [#h42edcb6]
#mycode2(){{
if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
}}
** for文 [#c69ffd4a]
#mycode2(){{
# いくつかの文字列の長さを測る:
list1 = ['cat', 'window', 'defenestrate']
for x in list1:
print x, len(x)
}}
** pass 文 [#q172fff8]
#mycode2(){{
pass # なにもしない
}}
** 関数の利用 [#v92b2fd1]
#mycode2(){{
# 戻り値のない関数
def hello(x,y):
print "hello world!"
# 戻り値のある関数
def add(x,y):
return x + y
}}
** モジュールの利用 [#me2895d5]
echotest.py
#mycode2(){{
def echo1():
print "test1!"
def echo2():
print "test2!"
}}
&br;
#mycode2(){{
# モジュールのインポート (拡張子を覗いたファイル名を指定)
import echotest
# モジュールで定義されたメソッドの利用
echotest.echo1()
# ローカルな名前に代入して利用
method1 = echotest.echo1
method1()
}}
** パッケージについて [#u26fe08a]
#TODO( __init__.py など)
** モジュール検索について [#i0a22cb3]
・モジュールはカレントディレクトリ、環境変数 PYTHONPATH の順に探される。
・実際には、モジュールは変数 sys.path で指定されたディレクトリのリストから検索される。
** パッケージの利用 [#h133d1e1]
パッケージ (package) は、Python のモジュール名前空間を
``ドット付きモジュール名 (dotted module names)'' を使って構造化する手段。
** モジュール検索PATHの追加 [#w1b02748]
#mycode2(){{
import sys,os
sys.path.append('ディレクトリ')
}}
** ファイル一覧 [#q322dc9e]
#mycode2(){{
# coding: utf-8
import sys,os
import glob
import re
path = os.path.abspath(os.path.dirname(__file__))
# globで検索
files = glob.glob(path + "/*.md")
for file in files:
print(file)
# os.listdirで検索
pattern = r".*\.md$"
files = os.listdir(path)
for file in files:
match = re.match(pattern , file)
if match:
print file
}}
** 呼び出し元ファイルのフルパスを取得する [#z9cf44ba]
#mycode2(){{
呼び出し元ファイルのフルパスを取得する
import inspect
print(inspect.stack()[1].filename)
}}
** 簡易Webサーバ [#h7ca0ee1]
サーバロジックを書きたい場合は [[pythonでWebサーバを書いてみる]] を参照。
#myterm2(){{
python -m http.server 8000 -b localhost
}}
※-b を指定しない場合は、localhost 以外にも公開される。( -b 0.0.0.0 と同じ)