今日もPythonは僕に冷たい

ちょっと興味が出てきたので,軽くテスト。

Python 2.3.5 (#1, Jan 13 2006, 20:13:11)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
>>> class Foo(object):
… def p(self):
… print “foo”

>>> a = Foo()
>>> a.p
<bound method Foo.p of <__main__.Foo object at 0x6edd0>>

Method.toString()ってわけだな。

>>> a.p()
foo
>>> class Bar(object):
… def q(self):
… print “bar”

>>> a.__class__ = Bar
>>> a.p()
Traceback (most recent call last):
File “<stdin>”, line 1, in ?
AttributeError: ‘Bar’ object has no attribute ‘p’
>>> a.q()
bar

なるほど,クラスを動的にすり替えられるわけだな。

>>> class Hoge1(object):
… p = 3

>>> a.__class__ = Hoge1
>>> a.p
3
>>> class Hoge2(object):
… p = 4

>>> a.__class__ = Hoge2
>>> a.p
4
>>> a.p = 40
>>> a.p
40
>>> a.__class__ = Hoge2
>>> a.p
40
>>> Hoge2.p
4

なるほど,インスタンスに対しての属性は,クラスを入れ替えたとしても,クラスに定義された初期値で上書きはされないということだな。
しかし・・・

>>> exit
‘Use Ctrl-D (i.e. EOF) to exit.’
>>> ^D
beloved:~ yoichiro$

またPythonに怒られた。やっぱり僕はRubyにしよう。

Trackback URL:

コメントを残す

コメントを投稿するにはログインしてください。

Get Adobe Flash playerPlugin by wpburn.com wordpress themes