python 类方法(classmethod)小实验代码
2012-05-21 10:50
357 查看
class c(object): foralll = 8 def __init__(self, i, forall): self.i = i self.test = 0 self.foralll = forall print self.i print self.foralll def do_print(self): print "OK" @classmethod def do_print_again(clss): print "OKOK" @classmethod def smthd(clss, i, forall): clss.foralll = forall print clss.foralll clss.do_print_again cc = c(0,0) cc.do_print() c.smthd(2, 3)
result:
0 0 OK OKOK 3python里面有两个概念,类和实例,凡是def XXX(self)的方法,以及self.XXX的变量都是只能由实例调用的实例就是指代码中的"cc", 是对类实例化后的结果。而带有@classmethod修饰符的方法,只能调用类中同样由@classmethod修饰符修饰的方法,和在init方法之前声明的那些变量(类变量?)相比较@staticmethod 就不能调用类中的任何值和方法了(二) 一个对比测试
class c(object): foralll = 8 def __init__(self): print self.foralll @classmethod def smthd(clss, i, forall): clss.foralll = forall print clss.foralll cc = c() print cc.foralll c.smthd(2, 3) print cc.foralll
result:
8833
class c(object):foralll = 8def __init__(self):self.foralll = 0 # differentialprint self.foralll@classmethoddef smthd(clss, i, forall):clss.foralll = forallprint clss.foralllcc = c()print cc.foralllc.smthd(2, 3)print cc.foralll
result:
0030
相关文章推荐
- python测量代码运行时间方法
- Python中staticmethod方法和classmethod方法区别
- 笨方法学习Python-习题23: 读代码
- python 类中@staticmethod,@classmethod和实例方法
- 高效开发Python扩展模块方法:用SWIG封装C/C++代码
- python2.7代码在win7_64环境下输出中文乱码解决方法
- Python实现判断一行代码是否为注释的方法
- python 解析html基础 HTMLParser库,方法,及代码实例
- 【Python入门】02—代码打包生成EXE文件的方法
- Python中用字符串调用函数或方法示例代码
- vim编译器中多行注释方法(尤其对python代码注释)
- 高效开发Python扩展模块方法:用SWIG封装C/C++代码
- 笨方法学习Python-习题18: 命名、变量、代码、函数
- 编写兼容 Python 2.x 和 3.x 代码的方法
- Python使用list的append和pop方法创建堆栈和队列实例代码
- Python实现比较两个文件夹中代码变化的方法
- 粗解python的@classmethod和@staticmethod及普通实例方法
- python 类中staticmethod,classmethod,普通方法
- python代码中的中文乱码解决方法
- 转:『Sklearn』数据划分方法及python代码