python的实例方法、类方法、静态方法

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 三种方法,除了实例方法只能被实例调用外,其余对于类和实例均可以被调用
2 实例方法第一个参数self
静态方法对参数无要求
类方法的第一个参数为类,一般用cls表示

你可能感兴趣的:(python的实例方法、类方法、静态方法)