トップ 一覧 ping 検索 ヘルプ RSS ログイン

Python コード片の変更点

  • 追加された行はこのように表示されます。
  • 削除された行はこのように表示されます。
!!!Python コード片
[Python 2.5]

!!重要
!HELP
*"対象"に調べたいオブジェクトを設定
*ライブラリ等の場合、importしてから使用する
 >>> help(対象) 

 >>> import fileinput
 >>> help(fileinput)
 Help on module fileinput:
 
 NAME
     fileinput - Helper class to quickly write a loop over all standard input fi
 es.
 
 FILE
     c:\python25\lib\fileinput.py
                 :

!属性の確認
*"オブジェクト"に調べたいオブジェクトを設定
 >>> dir(オブジェクト)

!!オブジェクト
!オブジェクトの型
,API,概要
,type(),【組み込み関数】オブジェクトの型を返す
 import os
 print 'os type:%s' %(type(os))
 fils = os.listdir('c:\work')
 print 'os.listdir type:%s' %(type(fils))
 print 'listdir[0] type:%s' %(type(fils[0]))
 
結果
 os type:<type 'module'>
 os.listdir type:<type 'list'>
 listdir[0] type:<type 'str'>

!!ディレクトリとファイル
!ディレクトリの内容を表示
,API,概要
,os.listdir,ディレクトリ内容のリストを取得
 import os
 fs = os.listdir('c:\work')
 for f in fs:
   print f 
 
!ディレクトリの内容を表示(2)
,API,概要
,os.path.isdir,パスのディレクトリ判定
,os.path.exists,パスの存在判定
,print 'C言語スタイルの書式文字' %(パラメータ),書式付出力

 import os
 basedir = 'c:\work'
 fils = os.listdir(basedir)
 print 'dir\texists\tpath'
 print '------------------'
 for fi in fils :
   p = basedir + os.sep + fi
   print '%s\t%s\t%s' %(str(os.path.isdir(p)), str(os.path.exists(p)), p)
 
!ファイルの内容を表示
*ディレクトリに含まれるファイルの内容を出力
,API,概要
,os.chdir,カレントディレクトリの変更
,os.path.abspath,絶対パスの取得
,open,【組み込み関数】ファイルを開く

""print の末尾に "," で、改行出力を抑制

 import os
 os.chdir('c:\work')
 fils = os.listdir('.')
 for fi in fils:
   p = os.path.abspath(fi)
   if not os.path.isdir(p) :
     print '===== %s =====' %(fi)
     f = open(p)
     try:
       for line in f:
         print line,
     finally:
       f.close()
 
!パスを生成

,API,概要
,os.path.join,2つ以上のパスを結合する。必要なら\を挿入

 join(a, *p)

 >>> import os
 >>> p = os.path.join('c:\\', 'work', 'test')
 >>> print p
 c:\work\test

!ディレクトリ判定
,API,概要
,os.path.isdir(path),ディレクトリか否かを判定

 >>> import os
 >>> os.path.isdir('c:\work')
 True

!ディレクトリの走査
 import os
 import pprint
 
 def trav(path, fn=''):
   l = []
   l.append(fn)
   d = os.path.join(path,fn)
   if os.path.isdir(d):
     for f in os.listdir(d):
       l.append(trav(d,f))
   return l
 
 l = trav('C:\\', 'Python25')
 pprint.pprint(l)

!!オブジェクト指向
!クラスを使用
,API,概要
,class クラス名:,クラスを作成
,def メソッド名(self,引数・・・),メンバ関数
,def __init__(self),インスタンス初期化

*メンバ関数の先頭引数にはインスタンスの参照(self)を指定する
*クラス名()でインスタンスを作成
 class Person:
   def __init__(self):
     print 'wake up'
 
   def greet(self):
     print 'hello.'
 
 x = Person()
 x.greet()
結果
 wake up
 hello.

!メソッドオブジェクト
*メソッドをオブジェクトとして扱う
 class Person:
   def greet(self):
     print 'hello.'
 
 x = Person()
 y = x.greet
 
 print type(y)
 y()
 
結果
 <type 'instancemethod'>
 hello.

!継承
,API,概要
,class 派生クラス名(基底クラス名):,基底クラスから派生クラスを作成

 class Person:
   msg = '...'
   def greet(self):
     print self.msg
 
 class Japanese(Person):
   msg = 'ohayo-'
 
 class American(Person):
   msg = 'hello.'
 
 x = Japanese()
 x.greet()
 
 y = American()
 y.greet()
結果
 ohayo-
 hello.

!多重継承
,API,概要
,class 派生クラス名(基底クラス名,基底クラス名,・・・):,基底クラス(複数)から派生クラスを多重継承して作成
,pass,処理がないのを明示

 class Person:
     def speak(self):
         print 'hello'
 
 class Bird:
     def fly(self):
         print 'flying in the sky'
 
 class BirdMan(Person, Bird):
     pass
 
 x = BirdMan()
 x.speak()
 x.fly()

!ポリモーフィズム
 class Animal:
   voice = '...'
   def cry(self):
     print self.voice
 
 class Cat(Animal):
   voice = 'nya-'
 
 class Dog(Animal):
   voice = 'wan'
 
 c = Cat()
 d = Dog()
 
 mypet = [c, d]
 for pet in mypet:
   pet.cry()
結果
 nya-
 wan
!!コレクション
!リストとスライス
,API,概要
,list(),リストの生成、[リストの内容,・・・]で宣言と同時に初期化
,[開始位置:終了位置:STEP],スライス。開始位置から終了位置までSTEPごとに切り出す

 #l = list()
 l = [6,5,2,3,1,4]
 l.append(7)
 l.append(8)
 l.sort()
 print l
 print l[::2]
 print l[1::2]
結果
 [1, 2, 3, 4, 5, 6, 7, 8]
 [1, 3, 5, 7]
 [2, 4, 6, 8]

!コンテナオブジェクトからリストを作成
*文字列は文字のコンテナオブジェクト 
 msg = 'this is message.'
 l = list(msg)
 print l
結果
 ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e', '.']
![タプル|http://ja.wikipedia.org/wiki/%E3%82%BF%E3%83%97%E3%83%AB]
*リストや配列と異なり、用途や型が異なるオブジェクトをひとつにまとめるために使われる
*C言語の構造体を匿名にしたようなものと考えることができる
*ひとつの「かたまり」として変数に代入できる
*関数の返り値として使うこともできる。これによって、複数の値を返す関数を実現することができる
*リストと同様に、個々の要素を添え字によって参照できる
*あくまで「ひとつの値」であるため、一度構築したら中の値を変更することができない

 t1 = 1,'one',
 t2 = 2,'two',
 t3 = 3,'tree',
 
 t  = t1,t2,t3,
 print t
結果
 ((1, 'one'), (2, 'two'), (3, 'tree'))

!Set
 s = set('aaaabbbbccccddd')
 print s
結果
 set(['a', 'c', 'b', 'd'])
!!データベース
!データベース(SQLite)の使用
 #!python2.5
 # -*- coding: utf-8 -*-
 import sqlite3
 
 con = sqlite3.connect('/work/py/test.db')
 
 #create database in RAM
 #con = sqlite3.connect(':memory:')
 
 con.execute("create table test (id  text, value text, note text)")
 
 con.execute("insert into test values('1','aaa','01')")
 con.execute("insert into test values('2','bbb','02')")
 con.execute("insert into test values('3','ccc','01')")
 
 con.commit()
 
 p = ('01',)
 c = con.cursor()
 c.execute("select * from test where note=?", p)
 
 for r in c:
 	print r
 
 con.close()
結果 
 (u'1', u'aaa', u'01')
 (u'3', u'ccc', u'01')
*Python