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的世界。
    欢迎大家批评指正,谢谢大家关注!

     

  • 相关阅读:
    jQuery $.each用法
    JSON.parse()和JSON.stringify()
    创建对象,初始化对象属性,给节点分派一个合成事件
    javascript 兼容W3c和IE的添加(取消)事件监听方法
    tomcat发布后项目classes下无编译文件
    纯css实现计数器效果
    js点击元素输出对应的index
    鼠标滚轮监听防“抖动”
    原生dom的querySelector、querySelectorAll方法
    spring mvc 通过url传来的参数乱码的解决方法
  • 原文地址:https://www.cnblogs.com/LaoYuanPython/p/11087696.html
Copyright © 2011-2022 走看看