ITメモ
Python / パイソン




【Python】クラス(class)

【Python】
クラス(class)




クラス(class)とは





クラス(class)の書式


Python の「クラス(class)」
クラス名は慣習的に大文字で始める。
クラス定義の冒頭には、「"""..."""」(ドキュメントストリング) を記述することが可能。


class SampleClass:
"""ドキュメントスリングのテキスト"""

def __init__(self): # コンストラクタ
self.name = ""

def Func01(self): # メソッド
return "Test"




クラス変数・インスタンス変数(attribute)


クラスは、「インスタンス変数」と「クラス変数」を持つことが可能。
「インスタンス変数」は、「インスタンス.変数名」で表示。
「インスタンス変数」は、インスタンス毎に独立の変数。
インスタンス変数は、コンストラクタ「__init__」の中で初期化コードを記述することで、インスタンス時に初期化される。



コンストラクタ(__init__)


「__init__()」メソッドは、クラスのインスタンスが生成された際に呼び出され、「コンストラクタ」ともいう。



文字列化(__str__)


「__str__()」は、インスタンスを暗黙的に文字列に変換する。



クラス階層


「Python」クラスは、すべて「object 」をルートとするクラス階層。

object

+- int
| +- bool
+- long
+- float
+- complex
+- basestring
| +- str
| +- unicode
+- list
+- tuple
+- dict
+- file
+- BaseException
+- SystemExit
+- KeyboardInterrupt
+- GeneratorExit
+- Exception
+- StopIteration
+- StandardError
| +- BufferError
| +- ArithmeticError
| | +- FloatingPointError
| | +- OverflowError
| | +- ZeroDivisionError
| +- AssertionError
| +- AttributeError
| +- EnvironmentError
| | +- IOError
| | +- OSError
| | +- WindowsError (Windows)
| | +- VMSError (VMS)
| +- EOFError
| +- ImportError
| +- LookupError
| | +- IndexError
| | +- KeyError
| +- MemoryError
| +- NameError
| | +- UnboundLocalError
| +- ReferenceError
| +- RuntimeError
| | +- NotImplementedError
| +- SyntaxError
| | +- IndentationError
| | +- TabError
| +- SystemError
| +- TypeError
| +- ValueError
| +- UnicodeError
| +- UnicodeDecodeError
| +- UnicodeEncodeError
| +- UnicodeTranslateError
+- Warning
+- DeprecationWarning
+- PendingDeprecationWarning
+- RuntimeWarning
+- SyntaxWarning
+- UserWarning
+- FutureWarning
+- ImportWarning
+- UnicodeWarning
+- BytesWarning