Python OOP(3) staticmethod和classmethod统计实例

 

staticmethod 统计实例

 

#!python2
#-*- coding:utf-8 -*-


class c1:
    
    amount_instance=0
    
    def __init__(self):
        c1.amount_instance+=1
        
    @staticmethod
    
    def printresult():
        print "Amount of Instance: " ,c1.amount_instance

        
class sub1(c1):
    
    #此处定义没有作用,因为只会引用c1中amount_instance
    
    amount_instance=0
     
    @staticmethod
    
    def printresult():
        
        print "call by sub1"
        
        c1.printresult()
 

class sub2(c1):
    
    #此处定义没有作用,因为只会引用c1中amount_instance
    
    amount_instance=0   
                 
        
i1,i2=c1(),c1()

i1.amount_instance
Amount of Instance:  2

c1.amount_instance

Amount of Instance:  2


s1,s2=sub1(),sub1()

s1.printresult()

call by sub1
Amount of Instance:  4

sub1.printresult()

call by sub1
Amount of Instance:  4


s3=sub2()

s3.printresult()

Amount of Instance:  5

 

classmethod 统计实例

 

#!python2
#-*- coding:utf-8 -*-
#利用类方法管理每个类的实例计数器
#父类使用一个类方法来管理状态信息,该信息根据树中的类不同而不同,而且储存在类上
#类方法调用的是当前类的amount_instance而不是父类中的amount_instance


class c1:
    
    amount_instance=0
    
    @classmethod
    
    def printresult(cls):
        
        cls.amount_instance+=1

    def __init__(self):
        
        self.printresult()
        
             
class sub1(c1):
    
    amount_instance=0
     
    def __init__(self):
        
        c1.__init__(self)
    
 

class sub2(c1):
    
    amount_instance=0   
    
        
i1=c1()

i1.amount_instance
1

c1.amount_instance
1

s1,s2=sub1(),sub1()

s1.amount_instance
2
sub1.amount_instance
2
c1.amount_instance
1

s3,s4,s5=sub2(),sub2(),sub2()

s3.amount_instance
3

c1.amount_instance
1
        
        

所以

1)静态方法:适用于处理一个类的本地数据

2)类方法:适用于处理类层级中每个类的数据

 

posted on 2017-03-03 15:25  大大的橙子  阅读(144)  评论(0编辑  收藏  举报

导航