2009-06-30(火)
間違いやすいPythonのクラス変数とインスタンス変数
すごい昔のエントリですが、コメントできなくなってたんでTBで。
やっぱり、インスタンス変数(クラス変数も!)は先頭で宣言しないと気持ち悪い。だから、初期化の必要がなくても以下のように書いておく。
class Hoge: #名前 name = None def __init__(self, name): self.name = name
気持ちはとてもとてもよくわかるんですけど、class宣言の中に変数を置いてもそれはあくまでもclassオブジェクトに紐づく値となってしまい、インスタンスの変数とはなりません。もちろん、わかってて使うなら大丈夫ですけど。
>>> class Hoge(object): ... foo = 10 >>> hoge1 = Hoge() >>> Hoge.__dict__.items() [('__dict__', <attribute '__dict__' of 'Hoge' objects>), ('__module__', '__main__'), ('foo', 10), ('__weakref__', <attribute '__weakref__' of 'Hoge' objects>), ('__doc__', None)] # ↑ここにfooはあるけど・・・ >>> hoge1.__dict__ {} # ↑hoge1はfooを持ってない
ドキュメントにも言及されてて、デフォルト値として使ってもいいけどミュータブルな値を使うと予期しない結果になると書かれてます。
Variables defined in the class definition are class variables; they are shared by all instances.
To create instance variables, they can be set in a method with self.name = value.
...中略...
Class variables can be used as defaults for instance variables, but using mutable values there can lead to unexpected results.
トラックバック - http://d.hatena.ne.jp/hiratara/20090630/1246332064
リンク元
- 125 http://d.hatena.ne.jp/ya_ken/20080703
- 95 http://www.google.co.jp/search?q=python+クラス変数 インスタンス変数&lr=lang_ja&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:ja:unofficial&client=firefox
- 77 http://www.google.co.jp/search?hl=ja&q=python+クラス&lr=
- 55 http://www.google.co.jp/search?hl=ja&client=firefox-a&rls=org.mozilla:ja:official&hs=2JX&q=python+class&btnG=検索&lr=lang_ja
- 51 http://www.google.co.jp/search?hl=ja&q=python+インスタンス+初期化&btnG=検索&lr=lang_ja&aq=f&oq=
- 33 http://www.google.co.jp/search?hl=ja&source=hp&q=python+クラス&lr=&aq=f&oq=
- 29 http://www.google.co.jp/search?sourceid=chrome&ie=UTF-8&q=python+class
- 28 http://return0.dyndns.org/log/
- 28 http://www.google.co.jp/search?hl=ja&q=python+変数定義&lr=
- 25 http://www.google.co.jp/search?sourceid=navclient&hl=ja&ie=UTF-8&rlz=1T4GGLL_jaJP322JP322&q=python+クラス





