python 类方法(classmethod)小实验代码

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
        3



python里面有两个概念,类和实例,凡是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:
8
8
3
3

class c(object):
    foralll = 8
    def __init__(self):
        self.foralll = 0 # differential
        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: 
0
0
3
0


你可能感兴趣的:(python 类方法(classmethod)小实验代码)