Pythonのdocstringとプライベート変数
いろいろ教えてもらったので復習がてらメモ
point.py
"""Point class This is the Point class """ class Point: __x = 0.0 __y = 0.0 z = 0.0 def __init__(self, x1, y1, z1) : self.__x = x1 self.__y = y1 self.z = z1 def toString(self) : return '(' + str(self.__x) + ', ' + str(self.__y) + ', ' + str(self.z) + ')'
というクラスをつくったとします。__x,__yがプライベート変数です。"""で囲まれている部分がdocstringです。
参考:プライベートメンバ
まずインタプリタを起動します。
$ python Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> dir() ['__builtins__', '__doc__', '__name__']
pointモジュールを読み込んでdocstringを見た後ヘルプを見ます。
>>> import point >>> dir() ['__builtins__', '__doc__', '__name__', 'point'] >>> dir(point) ['Point', '__builtins__', '__doc__', '__file__', '__name__'] >>> point.__doc__ 'Point class\n\nThis is the Point class\n' >>> help(point) Help on module point: NAME point - Point class FILE /Users/Shared/point.py DESCRIPTION This is the Point class CLASSES Point class Point | Methods defined here: | | __init__(self, x1, y1, z1) | | toString(self) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | z = 0.0 (END)
おお! docstringが表示されてますね。あとプライベート変数が表示されてないですね。
次にインスタンスを作ってtoStringメソッドを呼び出してみます。普通ですね。
>>> p=point.Point(1, 2, 3) >>> dir() ['__builtins__', '__doc__', '__name__', 'p', 'point'] >>> p.toString() '(1, 2, 3)'
プライベート変数にアクセスすると怒られます。パブリック変数はOKです。
>>> p.x Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Point instance has no attribute 'x' >>> p.z 3
でもこんなふうにアクセスできます。_Point__xという形式を難号化 (mangle)っていうみたいです。
参考:http://www.python.jp/doc/nightly/tut/node11.html#SECTION0011400000000000000000
>>> dir(p) ['_Point__x', '_Point__y', '__doc__', '__init__', '__module__', 'toString', 'z'] >>> p._Point__x 1
まとめ:
docstringはJavadocとは異なり属性ですね。カプセル化は破れるけど破っちゃだめよということでしょう。Pythonたんは性善説を信じているようです。スバラシ!