>>> class Point:
... format = "%s [X:%s Y:%s]"
...
... def __init__(self, x, y):
... self.str = "Point"
... self.set(x, y)
...
... def set(self, x, y):
... self.__x = int(x)
... self.__y = int(y)
...
... def show(self):
... print Point.format % (self.str, self.__x, self.__y)
...
>>>
>>> p1 = Point(2, 6)
>>> p2 = Point(1,9)
>>>
>>> p1.show()
Point [x=2 y=6]
>>> p2.show()
Point [x=1 y=9]
>>>
>>> p1.str = "座標"
>>> p1.show()
座標 [x=2 y=6]
>>> p2.show()
Point [x=1 y=9]
>>>
>>> Point.format = "%s [x=%s y=%s]"
>>> p1.show()
座標 [x=2 y=6]
>>> p2.show()
Point [x=1 y=9]
>>>
>>> p1._Point__x
2
- クラス定義の開始はclass クラス名:
- クラス内で関数を定義すると、メソッドになる
- メソッドの第一引数は、self(そのメソッドのインスタンス)
- メソッドを呼び出す際には、インスタンスを渡す必要はない
- __init__( )はインスタンス生成直後に呼び出される
- インスタンスの属性(データまたはメソッド)はインスタンス名.属性名で参照する
- クラス変数とはクラスオブジェクトの属性、クラス名.属性名で参照する
- インスタンスの属性をプライベートにするには、名前を__で始まり__で終わらないものにする
- プライベートな属性は、インスタンス名.__クラス名_属性名で参照する