Pythonのクラスの挙動を調べる:class構文の外でクラスにメンバ関数を追加(2)
今度は、別のモジュールで定義したクラスにメンバ関数を追加してみる。
[Macintosh:~]$ python
Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
# importすることで定義されたクラスは、その名前空間内に閉じこめられる
>>> import foobar
>>> print foobar.FooBar
<class 'foobar.FooBar'>
# 名前空間が異なっていても、名前空間さえ指定すればメンバ関数を追加できる
>>> f = foobar.FooBar()
>>> f.show_name()
I'm FooBar.
>>> def rename(self,new_name):
... self.name = new_name
...
>>> foobar.FooBar.rename = rename
>>> f.rename("john")
>>> f.show_name()
I'm john.
大体予想通りの結果ですな。