■
pythonについてメモ
クラスの実体と、クラスの実体からインスタンス化されたオブジェクトは別モノ。
至極当然のことだけど。
a = 'hello world'
などとやると、内部では a という変数に hello world という値をもった「str型オブジェクトへの参照」が格納されることになる。
>>> 'hello world' 'hello world' >>> type('hello world') <type 'str'> >>> 'hello world'[:5] 'hello' >>> 'hello world'.split(' ') ['hello', 'world']
なので、上のように、文字列に対していきなりドットで繋いでstr型が持っている機能が使えるということが理解できる。
このstrというのは
http://docs.python.org/library/functions.html
ここで紹介されている、ビルトイン関数というもので、ここらへんをひと通り理解したら色々捗りそう。
>>> object <type 'object'> >>> str <type 'str'> >>> str.__bases__ (<type 'basestring'>,) >>> basestring <type 'basestring'> >>> basestring.__bases__ (<type 'object'>,)
strを遡っていくと、まぁ、結局はobject。
ちなみにobjectの__bases__はtupleだった。
>>> class A(object): ... test_val = 'hello world' ... pass ... >>> A <class '__main__.A'> # Aが定義された >>> A.test_val 'hello world' # Aの中身の値も当然、保持されている >>> type(A) <type 'type'> >>> A.__bases__ (<type 'object'>,) # 新スタイルクラスを使ってるよ >>> instance = A() >>> instance <__main__.A object at 0x2b171ccf4b90> # 実体が生成された >>> instance.test_val 'hello world' >>> type(instance) <class '__main__.A'> >>> A.test_val 'hello world' >>> instance.test_val 'hello world' >>> A.test_val = 'goodbye world' # Aのtest_valを直接アクセスして書き換えてみる >>> A.test_val 'goodbye world' >>> instance.test_val 'goodbye world' # インスタンスのtest_valも変わった! >>> instance2 = A() >>> instance2.test_val 'goodbye world' >>> instance.test_val = 'foobar' # instance側のtest_valを書き換えてみる >>> A.test_val 'goodbye world' # 変化無し >>> instance.test_val 'foobar' # ちゃんと書き換わってる >>> instance2.test_val 'goodbye world' # 変化無し
python面白い!