pythonのインスタンスメソッド、クラスメソッド、静的メソッド

870 ワード

In [48]: class TestStaticMethod():
   ....:     @staticmethod
   ....:     def foo():
   ....:         print'static foo is called'
   ....:     @classmethod
   ....:     def foo2(cls):
   ....:         print'class foo2 is called'
   ....:         print'foo2 is part of calss',cls.__name__
   ....:         

In [49]: Te
Templates/        TestStaticMethod  

In [49]: TestStaticMethod.foo()
static foo is called

In [50]: TestStaticMethod.foo2()
class foo2 is called
foo2 is part of calss TestStaticMethod

In [51]: test = TestStaticMethod()

In [52]: test.foo()
static foo is called

In [53]: test.foo2()
class foo2 is called
foo2 is part of calss TestStaticMethod


まとめ:1 3つの方法は、インスタンスメソッドがインスタンスによってのみ呼び出されるほか、クラスとインスタンスに対して2インスタンスメソッドを呼び出すことができる最初のパラメータself静的メソッドパラメータに対してクラスを要求しない方法の最初のパラメータはクラスであり、一般的にclsで表される.