Hatena::Grouppython

zorioの日記

 | 

2010-03-21

スタティックメソッドとクラスメソッド

22:30

参考:

http://jutememo.blogspot.com/2008/09/python-classmethod-staticmethod.html

スタティックメソッドの場合、メソッドを定義したクラスにしかアクセスできない

# -*- encoding: utf-8 -*-
class Base:
  isInitialized = False
  @staticmethod
  def Initialize():
    if Base.isInitialized == False:
      print "This is initialized now"
      Base.isInitialized = True
    else:
      print "This is already initialized"
    

class Derived1(Base):
  pass
  
class Derived2(Base):
  pass

Derived1().Initialize()
Derived1().Initialize()
Derived2().Initialize()
Derived2().Initialize()
実行結果:最初に作ったDerived1の時しか実行されない
This is initialized now
This is already initialized
This is already initialized ←ここが違い
This is already initialized

クラスメソッドは、実際に実行されたクラスにアクセスできる

# -*- encoding: utf-8 -*-
class Base:
  isInitialized = False

  @classmethod
  def Initialize(cls):
    if cls.isInitialized == False:
      print str(cls) + " is initialized now"
      cls.isInitialized = True
    else:
      print str(cls) + " is already initialized"

class Derived1(Base):
  pass
  
class Derived2(Base):
  pass

Derived1().Initialize()
Derived1().Initialize()
Derived2().Initialize()
Derived2().Initialize()
実行結果:最初のDerived1、最初のDerived2でそれぞれ実行される。
__main__.Derived1 is initialized now
__main__.Derived1 is already initialized
__main__.Derived2 is initialized now  ←ここが違い
__main__.Derived2 is already initialized

サブクラスでクラス変数初期化をやりたいんだけどその初期化の処理は基底クラスに書きたい、って事が実際にあったので、そういう時に便利なんじゃないかな。

PankajPankaj2012/09/21 11:00AFAIC that's the best aneswr so far!

afupeujpdrafupeujpdr2012/09/21 23:46MTalJW <a href="http://ycxcqxoejgee.com/">ycxcqxoejgee</a>

dqhbxkdqhbxk2012/09/22 11:38o1dD2K , [url=http://yvhtscoxhqvw.com/]yvhtscoxhqvw[/url], [link=http://ebwkccusvzdq.com/]ebwkccusvzdq[/link], http://gjkculbqdbcg.com/

ibhngctibhngct2012/09/23 05:20RLMPm7 <a href="http://kukgevixdgyr.com/">kukgevixdgyr</a>

egncghfcbegncghfcb2012/09/23 17:029nRjzr , [url=http://maxnbuutmooq.com/]maxnbuutmooq[/url], [link=http://gienvxcvupak.com/]gienvxcvupak[/link], http://rcrbtronnqss.com/

 |