class 定義†
class <class-name>:
def __init__(self): # 初期化メソッド
self.value = 0;
print( "Initialize done..." );
def hoge(self, fuga):
...
- 各クラスメソッドの第1引数には、必ず self を入れること。
- "self" とは、クラス内で参照される、クラス自身のインスタンス。C++ の this のようなもの。
- アトリビュート(C++ で言うところのメンバ変数)を用意するときは、 __init__() 関数内で初期化する。宣言はない。
演算子の定義†
class CHoge:
def __init__(self):
self.x = 0;
self.y = 0;
# + 演算子の定義
def __add__(self, other):
return CHoge( self.x + other.x, self.y + other.y );
各種演算子を定義する特別関数一覧†
Operator | Special method |
self + other | __add__(self, other) |
self - other | __sub__(self, other) |
self * other | __mul__(self, other) |
self / other | __div__(self, other) or __truediv__(self,other) if __future__.division is active. |
self // other | __floordiv__(self, other) |
self % other | __mod__(self, other) |
divmod(self,other) | __divmod__(self, other) |
self ** other | __pow__(self, other) |
self & other | __and__(self, other) |
self ^ other | __xor__(self, other) |
self | other | __or__(self, other) |
self << other | __lshift__(self, other) |
self >> other | __rshift__(self, other) |
bool(self) | __nonzero__(self) (used in boolean testing) |
-self | __neg__(self) |
+self | __pos__(self) |
abs(self) | __abs__(self) |
˜self | __invert__(self) (bitwise) |
self += other | __iadd__(self, other) |
self -= other | __isub__(self, other) |
self *= other | __imul__(self, other) |
self /= other | __idiv__(self, other) or __itruediv__(self,other) if __future__.division is in effect. |
self //= other | __ifloordiv__(self, other) |
self %= other | __imod__(self, other) |
self **= other | __ipow__(self, other) |
self &= other | __iand__(self, other) |
self ^= other | __ixor__(self, other) |
self |= other | __ior__(self, other) |
self <<= other | __ilshift__(self, other) |
self >>= other | __irshift__(self, other) |
アトリビュートの隠蔽†
- 先頭に "_" を1個付ける
- 慣習的に、「外部から直接参照・代入してはいけないもの」と見做すことになっている。
実際にはクラス外部から操作出来てしまう。
class CTest2:
def __init__(self,x,y):
self.m_x = x;
self.m_y = y;
def Start(self):
self._StartSub();
def _StartSub(self):
print "StartSub\n";
def _PrintPropSub(self):
print "[X:", self.m_x, "][Y:", self.m_y,"]";
def PrintProp(self):
self._PrintPropSub();
def __PrintProp(self):
print "__PrintProp()";
self._PrintPropSub();
c2 = CTest2(10,20);
c2.Start();
c2.PrintProp();
c2._PrintPropSub(); # 実行時、ここではエラーにならない
c2.__PrintPropSub(); # 実行時、ここでエラーになる
クラスの継承†