• 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)类方法:适用于处理类层级中每个类的数据

  • 相关阅读:
    关于不重启Tomcat自动加载改变的class文件
    Oracle数据库查询优化方案
    NavBarControl
    Spring Boot 热部署
    JSR303定义的校验类型
    C# JSON的序列化与反序列化
    常用正则表达式大全——包括校验数字、字符、一些特殊的需求等等
    什么是窗口句柄
    luffy前台配置
    luffy后台相关设置
  • 原文地址:https://www.cnblogs.com/dadadechengzi/p/6496882.html
Copyright © 2020-2023  润新知