Pythonでは関数ベースでもクラスを使ったオブジェクト指向でもプログラムも書けるようになっています。 小規模のツールなどでは関数のみを利用しても十分ですが、ある程度複雑な処理や、再利用しやすいプログラムを書くならクラスを使った方が便利です。 こちらではPythonのクラスについて簡単にまとめます。 *基本 [#u61fc2c4] クラスの定義は「class」で行います。 メソッドの定義は「def」です。 コンストラクタは「__init__」で、インスタンス化に「new」は不要です。 class TestClass: def __init__(self): print "construct!" testClass = TestClass() 結果 construct! また全てのメソッドは「self」を引数としなければならず、これは自身のインスタンスを表します。 他の言語で言うところの「this」とほぼ同じです。 class TestClass: def whatIsSelf(self): print type(self) print self testClass = TestClass() testClass.whatIsSelf() 結果 <type 'instance'> <__main__.TestClass instance at 0x10c2a4bd8> この「self」を使ってクラス内のメソッドを呼びます。 多くの他言語の「this」と違って、省略することはできません。 class CallMethod: def method1(self): print "method1 called" def method2(self): self.method1() callMethod = CallMethod() callMethod.method2() 結果 method1 called クラス変数も定義できます。 クラス変数はクラス名でも「self」を含むインスタンスからでも参照可能です。 class ClassVariables: a = 1 b = 2 def __init__(self): print self.b self.a = 10 classVariables = ClassVariables() print ClassVariables.a print classVariables.a 結果 2 1 10 ここでインスタンスでそのクラス変数を参照するときには、もしインスタンスでその変数を変更していなければ初期値を参照し、そうでなければ変更後の値を参照します。 これは他のprototype型のクラス定義を採用している言語と同様です。 *参照の制限 [#y20ef82a] Pythonではprivateなどの参照範囲を制限する修飾子はサポートされていません。 代わりに「_」(アンダーバー)で始まる要素には慣習的にクラス外から参照しない(しようと思えばできる)、「__」(アンダーバー2つ)で始まる要素はクラス外から参照するとエラーになる、という命名ルールがあります。 class PrivateMethod: def __method(self): print "__method" def _method(self): self.__method() privateMethod = PrivateMethod() 「_」で始まるメソッドは参照可能(ただし非推奨)。 privateMethod._method() 結果 __method 「__」で始まるメソッドはクラス内からの呼び出しは可能ですが、外部から呼び出すとエラー。 privateMethod.__method() 結果 Traceback (most recent call last): File "class_test.py", line 42, in <module> privateMethod.__method() AttributeError: PrivateMethod instance has no attribute '__method' &font(Red){制作中}; *継承 [#u224ed0a] *クラスメソッドとスタティックメソッド [#o110c130]
(This host) = https://njf.jp