zoukankan      html  css  js  c++  java
  • 第7.18节 案例详解:Python类中装饰器@staticmethod定义的静态方法

    第7.18节 案例详解:Python类中装饰器@staticmethod定义的静态方法


    上节介绍了Python中类的静态方法,本节将结合案例详细说明相关内容。
    一、    案例说明
    本节定义了类StaticMethod,在类中定义了静态方法stmethod、类方法clsmethod和实例方法objmethod,重写了__new__(self)方法。演示内容包括:
    1.    在类方法clsmethod中通过cls和类名两种方式调用静态方法stmethod;
    2.    在实例方法objmethod中通过类名调用静态方法;
    3.    在重写的实例方法__new__中通过类名、self方式调用静态方法,并输出“self.__class__”的值,以此说明为什么不能通过“self.__class__.stmethod”进行调用。
    二、    案例代码

    class StaticMethod():
        objcnt1 = 0
    
        @staticmethod
        def stmethod():print("in stmethod")
    
        @classmethod
        def clsmethod(cls):
            print("in clsmethod")
            cls.stmethod() #类方法中使用cls调用静态方法
            StaticMethod.stmethod() #类方法中使用类名调用静态方法
    
        def objmethod(self):
            print("in objmethod")
            StaticMethod.stmethod() #实例方法中使用类名调用静态方法
        def __new__(self): 
            StaticMethod.stmethod()#实例方法中使用类名调用静态方法
            self.stmethod()#实例方法中使用self调用静态方法
            self.clsmethod()#实例方法中使用self调用类态方法
            print("self.__class__=",self.__class__) #观察new方法中self.__class__的值
            #self.__class__.stmethod() 此种方式不能使用
            return super().__new__(self)  
    
    sm1=StaticMethod()   
    sm1.clsmethod()#通过实例访问类方法
    sm1.objmethod()#执行实例方法
    sm1.stmethod()#通过实例访问静态方法
    sm1.__class__.stmethod()#通过实例.__class__访问静态方法

    三、    案例截屏
     

    本节结合案例详细对上节介绍的静态方法的定义和使用方法进行了演示,希望对大家理解相关知识有所帮助。
    老猿Python(https://blog.csdn.net/LaoYuanPython)系列文章用于逐步介绍老猿学习Python后总结的学习经验,这些经验有助于没有接触过Python的程序员可以很容易地进入Python的世界。
    欢迎大家批评指正,谢谢大家关注!

     

  • 相关阅读:
    Windows XP下 Android开发环境 搭建
    Android程序的入口点
    在eclipse里 新建android项目时 提示找不到proguard.cfg
    64位WIN7系统 下 搭建Android开发环境
    在eclipse里 新建android项目时 提示找不到proguard.cfg
    This Android SDK requires Android Developer Toolkit version 20.0.0 or above
    This Android SDK requires Android Developer Toolkit version 20.0.0 or above
    Android requires compiler compliance level 5.0 or 6.0. Found '1.4' instead
    Windows XP下 Android开发环境 搭建
    Android程序的入口点
  • 原文地址:https://www.cnblogs.com/LaoYuanPython/p/11087696.html
Copyright © 2011-2022 走看看