Top/Lang/Python/Class

目次

class 定義

class <class-name>:
    def __init__(self):    # 初期化メソッド
        self.value = 0;
        print( "Initialize done..." );

    def hoge(self, fuga):
        ...

演算子の定義

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 );

各種演算子を定義する特別関数一覧

OperatorSpecial 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)

アトリビュートの隠蔽

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();    # 実行時、ここでエラーになる

クラスの継承

メソッドのオーバーライド [override]

Super class の取得: super()


トップ   編集 凍結 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2019-06-09 (日) 16:59:05