Chinaunix首页 | 论坛 | 博客
  • 博客访问: 386036
  • 博文数量: 112
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 800
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-29 13:41
文章分类

全部博文(112)

文章存档

2020年(1)

2018年(10)

2017年(27)

2016年(18)

2015年(31)

2014年(25)

分类: Python/Ruby

2017-07-19 17:40:15


staticmethod和classmethod均被作为装饰器,用作定义一个函数为staticmethod还是classmethod
@staticmethod 表示静态方法,不需要实例化类,用类直接调用方法。
@classmethod 表示类方法

点击(此处)折叠或打开


  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. class Test(object):
  4.     def instance(self):
  5.         print "this is instance."
  6.     @staticmethod
  7.     def staticmethod(*arg):    #括号内没有self,也就无法访问实例变量、类和实例的属性;
  8.         print "this is staticmethod."
  9.         print ('static:',arg)
  10.     @classmethod
  11.     def classmethod(cls):    #括号内没有self,但必须有cls这个参数,能够访问类属性,但不能访问实例属性;
  12.         print "this is classmethod."
  13.         print ('class:',cls)
  14. if __name__ == "__main__":
  15.     a = Test()   #实例化
  16.     a.instance()    #调用实例方法
  17.     a.staticmethod()    #通过实例调用静态方法
  18.     Test.staticmethod()    #通过类自己调用静态方法
  19.     a.classmethod()    #通过实例调用类方法
  20.     Test.classmethod()    #通过类自身调用类方法


点击(此处)折叠或打开

  1. 输出内容:
  2. this is instance.
  3. this is staticmethod.
  4. ('static:', ())
  5. this is staticmethod.
  6. ('static:', ())
  7. this is classmethod.
  8. ('class:', <class '__main__.Test'>)
  9. this is classmethod.
  10. ('class:', <class '__main__.Test'>)

点击(此处)折叠或打开

  1. 类直接调用方法会报错:
  2. Test.instance()
  3. TypeError: unbound method instance() must be called with Test instance as first argument (got nothing instead)



阅读(522) | 评论(0) | 转发(0) |
0

上一篇:super()函数

下一篇:python封装和私有化

给主人留下些什么吧!~~