ホーム     戻る

第12章  クラス   オブジェクト指向

"TO HELEN

Helen, thy beauty is to me
Like those Nicean barks of yore,
That gently, o'er a perfumed sea,
The weary, wayworn wanderer bore
To his own native shore.

On desperate seas long wont to roam,
Thy hyacinth hair, thy classic face,
Thy Naiad airs have brought me home
To the glory that was Greece
And the grandeur that was Rome.

Lo! in yon brilliant window-niche
How statue-like I see thee stand,
The agate lamp within thy hand!
Ah, Psyche, from the regions which
Are Holy Land!

Edgar Allan Poe"

”事例で理解する ”

クラスとインスタンス

一つしかないクラス:一つしかないtimeクラス
一つのインスタンス:一つのtimeインスタンス
クラスとインスタンスの区別「一つの」

オブジェクト:データとその処理機能を一つにまとめたもの:一般的に「クラス」として定義する
クラス:オブジェクト設計図:
インスタンス:クラスという設計図から生成された実体のあるオブジェクトとい
        う実物

クラス組み込みのオブジェクトとおなじように扱えるようにする仕組
           み:  レコード、構造体
ユーザ定義型 :データと操作グループ      
     。実体(データ)と振る舞い(処理)を持った「もの」を表現。         
     :
クラスとはオブジェクトの種類を表すもの。メソッドが各
      クラスに定義されている。クラスはオブジェクトの雛型のような  

      
もの型と言い換えてもよい
。(高橋・後藤ruby)
      モジュールとの違い:インスタンスを持つ:継承できる

継承:すでに定義されているクラスを拡張して新しいクラスをつ
           くること。

サーバー:サーバーにプログラムを書いてユーザーはそれをログインする。
       テスト用のサーバーと稼働用のサーバーを分ける。
       確実なプログラムの使用法。
(1) 簡単な例

>>> a=[1,2,3]      リストオブジェクト[1,2,3]が生成:データは1,2,3


>>> a.append(4)    appendメソッド追加機能:appendが処理機能
>>> a
[1, 2, 3, 4]

 作る class クラス名  クラスの定義(クラスメソッド)

>>> class Myclass:            クラス定義     作る
      "A simple example class"
      i=12345                             
      def f(self):
           return 'hello world'

 >>> Myclass.i               クラスへのアクセス 参照する    
12345
>>> Myclass.f
<unbound method Myclass.f>      エラー表示

>>> x.f()                              参照する    
'hello world'

>>>class Address:
       def __init__(self,zip,pr,ct,cn):    self:属性としてインスタン
                            ス変数を                     
                            自由に設定可
                            -init-()メソッドでインスタンス
                            変数                       
                            の初期化を行う

                 
  self.zip_Code=zip
  self.Prefecture=pr
  self.city=ct
  self.Cho_Number=cn

 
addr=Address("123-4567","神奈川県","川崎市高津区溝口",3)
print addr.city,addr.Cho_Number,"丁目":
 川崎市高津区溝口 3 丁目

 (2)クラスの解説(柴田pythonプログラミング入門)

classという語によって定義:defで関数を定義するのと同じ感覚
classの中で機能する専用の関数つまりメソッドを定義する。 そのclass専用のメソッドとなる。 

>>> class FirstClass :    #クラス名宣言
 a="hello"           #クラス変数クラスの属性aを定義
 def m(self) :         #メソッドmを定義
    print FirstClass.a   #メソッドmを定義クラスの内部でもクラス変数
                 #にアクセスするには、クラス変数の前にクラス
                 #名とドットをつける。

  >>> FirstClass.a     クラス変数にアクセス:クラス名.クラス変数
'Hello'
>>> FirstClass.a = "Goodbye"クラス変数の値を変更:
>>> FirstClass.a
'Goodbye'

>>> FirstClass.m             クラスの内容確認
<unbound method FirstClass.m>    mの実態がない
>>> i=FirstClass()                     インスタンスを生成
>>> i
<__main__.FirstClass instance at 0x00CCAFD0>
>>> FirstClass.m(i)
Goodbye
>>> i.m()               一般的な呼び出し法
Goodbye

>>> class SecondClass:
       a="hello"
       def m(self):     self:代名詞のようなもの:クラスを定              
                      義しているときは存在しないインスタン
                      スを仮に表す。:未来に生成されるイン
                      スタンスを一つの「self」で表現する

          self.a="Goodbye" インスタンス変数;その中だけで有効
          print self.a

  
>>> SecondClass.a            クラス変数にアクセス
'hello'
>>> SecondClass.a="GoodNight"   クラス変数に代入
>>> SecondClass.a
'GoodNight'
>>> i=SecondClass()           インスタンスを生成
>>> i.m()                   mを呼び出す
Goodbye                   インスタンス変数の値 
>>> SecondClass.a="GoodMorning"  aの値を変更
>>> SecondClass.a
'GoodMorning'
>>> i.m()                 メソッドmを呼び出す:値はかわらない:
                       クラス変数とインスタンス変数は内部    
                       では完全に区別されている。
Goodbye
>>> SecondClass.a
'GoodMorning'
>>>

>>> class thirdclass:
       a="hello"
       def m(self):
       print self.a

  
>>> thirdclass.a
'hello'
>>> i = thirdclass()
>>> i.m()
hello
>>> thirdclass.a="goodbye"
>>> thirdclass.a
'goodbye'
>>> i.m
<bound method thirdclass.m of <__main__.thirdclass instance at 0x00DB4FD0>>
>>> i.m()
goodbye
>>>

3)クラスの具体例

 (a)timeクラス

datetime  日付、時刻の基本形:モジュール名:クラス名

日付時刻情報の差を「d日とh時間m分s秒」形式で取得。

import datetime
a=datetime.datetime(2006,1,14,12,0,30)
b=datetime.datetime(2007,4,1,1,0,12)
td=b-a
dd=td.days
HH=td.seconds/3600
MM=td.seconds % 3600 /60
SS=td.seconds % 60
print ' %d日と  %d 時間 %d分  %d秒' %(dd,HH,MM,SS)

441日と  12 時間 59分  42秒

ある日付と別の日付の間の日数を取得。

import datetime
a=datetime.datetime(2005,4,29)
b=datetime.datetime(2007,1,31)
c=b-a
print c
642 days, 0:00:00         2005/4/29午前0時から2007/1/31午前0時まで
               の日数:指定された終わりの日は日数としてカウン
               トされない。

現在時刻を取得。

 import datetime
today=datetime.datetime.today()   最初のdatetimeはdatetimeモジュ
              ールの指定・次はその中のdatetimeクラスの指定・
print today

 2008-07-30 18:35:07.984000

書式を指定

import datetime
today=datetime.datetime.today()
today=today.strftime("%y/%m/%d/ %H:%M:%S")
print today
08/07/30/ 18:57:31
 

)特定のディレクトリの内容を取得

>>> import os
>>> os.listdir('c:\\')
['9249379a87f0170bffd4a3', 'account', 'AppFolder', 'AUTOEXEC.BAT', 'a_new', 'b96ecbbd37a1103e25bc', 'BASICw32', 'Books', 'BOOT.INI', 'bootfont.bin', 'BOOTLOG.PRV', 'BOOTLOG.TXT', 'BOOTSECT.DOS', 'Borland', 'BTI', 'Cache2', 'Cache3', 'Cache4', 'Cache5', 'CacheKit', 'CacheSys', 'CONFIG.SYS', 'Converter.exe', 'DB2', 'DELPHI', 'DLA.TAG', 'Documents and Settings', 'DRIVERS', 'drivez.log', 'FENGDIC', 'FlexLM', 'hiberfil.sys', 'HON.TMM.LNK', 'I386',

・・・・・

 (4)練習問題

1.生まれた年月日をたずねて、年齢を計算し、過ごしてきた誕生日それぞれに、おめでとう!をプレゼントする
しましょう。

(8)辞書デクショナリ ハッシュクラス

他言語ではhashハッシュ:連想配列

「キー」と「値」のペア。中括弧 { } キーの後ろに : 要素の後ろに  ,

>>> dic={1:'apple','tow':'orange'}
>>> dic
{1: 'apple', 'tow': 'orange'}

(9)少し複雑な例

>>> dic={'taro':{'age':18,'height':170},'jiro':{'age':23,'height':160}}
>>> dic
{'taro': {'age': 18, 'height': 170}, 'jiro': {'age': 23, 'height': 160}}

あとから追加 

>>> dic={}
>>> dic[1]='apple'
>>> dic['tow']='orange'
>>> dic
{1: 'apple', 'tow': 'orange'}
>>>

タプルをキーに

 >>> dic={}
>>> dic[(1,2)]=3                                タプルは不変なのでキーとなる
>>> dic
{(1, 2): 3}

マージ

 >>> a={'a':'x','b':'y','c':'z'}
>>> b={1:'one',2:'tow','a':'A'}
>>> a.update(b)
>>> a
{'a': 'A', 1: 'one', 'c': 'z', 'b': 'y', 2: 'tow'}   キーが存在した要素は取替
                         え、キーのない要素は追加される
>>>

タプルとsum()関数

>>> a=(123,456,789)
>>> sum(a)
1368

reversed()とreverse()

>>> list(reversed([1,2,3]))   reversed()はリストなどの引数をとり、list
                    関数で変換する。
[3, 2, 1]
>>> a=[1,2,3]
>>> a.reverse()          reverse()はリストメソッドであり、指定した
                    リストの内容自体を書き換える。
>>> a
[3, 2, 1]
>>>
>>> >>> list(reversed(['a','b','c']))
['c', 'b', 'a']
>>> a=['a','b','c']
>>> a.reverse()
>>> a
['c', 'b', 'a']

(10)文字列に関していろいろ

>>> da_man=['Mr.T',1,2,3,4,5]
>>> big_T=da_man[4]
>>> print big_T
4

>>> chr(84)
'T'

(2)モジュール

モジュール:
プログラミングの4ッ目の基本構造(順次実行・ループ・分岐・モジュール)再利用可能なコードを集めてパッケージ化したもの

関数の再利用:関数の独立性を高める:ある機能を分離して別のファイルに整理したもの:関数のサンプルをモジュールに変換

クラス
との違い:
モジュールはインスタンスを持たない
        モジュールは継承できない

モジュール
クラスは実体(データ)と振舞い(処理)を持った「もの」を表現する。モジュールは処理の部分だけをまとめるもの
モジュールの使い方:
名前空間の提供:グローバルな名前空間に別の名前空間を作成。
名前空間:メソッド・定数・クラスの名前がぶつからないようにする。名前のコ
            レクション
。(高橋・後藤・ruby)

使う   参照する:        モジュール名.メソッド名(引数)

作る

(1)プローシージャー・関数としてのモジュールの使う
 
 
ライブラリー
言語に付属している関数
 引数:関数の内部変数・関数の呼び出し時に渡す値

>>> c=" "
>>> s="a short string"
>>> import string             stringモジュール
>>> print string.split(s,c)        split関数 s、c 引数
['a', 'short', 'string']
>>>

>>> times="MORNING:EVENING:AFTERNOON"   文字列
>>> periods=string.split(times,":")  split関数 times : 引数    
>>> print "good---",periods[1]    文字列インデックス[1]参照
good--- EVENING

>>> x=2                                        基数2
>>> for y in range(0,11):
 print pow(x,y)              2のy階乗

 
1
2
4
8
16
32
64
128
256
512
1024

>>> import string                stringモジュールを呼び出す
>>> dir(string)         
dir関数・有効な名前(関数)のリスト表示 
['Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill']

(2)モジュールを使う

>>> import math           使う  
>>> print math.pi
3.14159265359
>>> print math.sqrt(2)
1.41421356237

モジュール名を記述せず、関数、変数を直接利用したいとき
from文を使ったimport:

>>> from math import sin,radians
>>> 10*20*sin(radians(45))/2
70.710678118654741

(3)モジュールを作る(アラン・ゴールド・python)

pythonのモジュールはpython文が記述されたテキストファイル
ほとんどの場合記述された文は関数定義

>>> from sys import*      sysモジュールをコピー

(a)エディターにテキストを記述する

def print_table(multiplier):
    print "---%dの掛け算表---" % multiplier
    for n in range(1,13):
        print"%dx%d=%d" % (n,multiplier,n*multiplier
)

(b)timestab。pyという名前で保存する。

(c)pythonプロンプトに入力する

>>> import timestab 

>>> timestab.print_table(12)

環境変数PYTHONPATH作成し、
timestab.pyの置いてあるデレィクトリをそこに設定

その他

pythonのクラス  について「 HPで紹介文があります。

ホーム     戻る