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表示

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容