zoukankan      html  css  js  c++  java
  • python基础学习——静态方法、类方法

    最近温故了一下 python 基础知识,有新的理解,整理在此,以便以后查阅或纠正。

    本文描述一下静态方法和类方法,引出装饰器的概念,在下一篇博文中记录。


    先举例,看效果:

     1 class MyClass:
     2     def smeth():
     3         print('This is a static method')
     4     smeth = staticmethod(smeth)
     5 
     6     def cmeth(cls):
     7         print('This is a class method of', cls)
     8     cmeth = classmethod(cmeth)
     9 
    10 # 或用装饰器
    11 class MyClass:
    12     @staticmethod
    13     def smeth():
    14         print('This is a static method')
    15 
    16     @classmethod
    17     def cmeth(cls):
    18         print('This is a class method of', cls)

    定义这些方法后,就可像下面这样使用它们(无需实例化类):

    In [24]: MyClass.smeth()
    This is a static method
    
    In [25]: MyClass.cmeth()
    This is a class method of <class '__main__.MyClass'>

    上一篇文章提到的例子中出现的报错,可以用类方法包装一下消除,而用静态方法不可,其实问题不是这样的。

    In [31]: class Foo:
    ...: @classmethod
    ...: def func(cls):
    ...: print('This is class method')
    
    @staticmethod
    def stat():
      print('This is static method')
    
    def cust(self):
      print('If you want to call me, write some agrs here')
    
    In [32]: Foo.func()
    This is class method
    In [33]: Foo.stat()
    This is static method
    In [34]: Foo.cust()
    ---------------------------------------------------------------------------
    TypeError Traceback (most recent call last)
    <ipython-input-72-2f40225d37e1> in <module>()
    ----> 1 Foo.cust()
    
    TypeError: cust() missing 1 required positional argument: 'self'
    
    In [35]: Foo.cust(123)
    If you want to call me, write some agrs here

    之所以出现这种情况,就在于静态方法和类方法创建的过程,它们分别包装在 staticmethod 和 classmethod 类的对象中。
      静态方法的定义中没有参数 self,可直接通过类来调用;
      类方法的定义中包含类似于 self 的参数,通常被命名为 cls。对于类方法,也可通过对象直接调用,这时参数 cls 将自动关联到类。
      而普通的方法则需要传递一个 self 参数,否则就会报错

    说了这么多,静态方法和类方法在编程中起什么作用,或是哪些情况下要用到它们?
      我个人缺少编程的经验,日常项目练习中也很少用到这个方法,所以只能拾人牙慧,摘录如下:

      在 Python 中,静态方法和类方法以前一直都不太重要,主要是因为从某种程度上说,总是可以使用函数或关联的方法替代它们,而且早期的 Python 版本并不支持它们。

      因此,虽然较新的代码没有大量使用它们,但它们确实有用武之地(如工厂函数),因此你或许应该考虑使用它们。--摘自《python基础教程第三版》

    以下两位博主的总结很清晰易懂,可做参考

    Done博主   ITxiaoke博主

  • 相关阅读:
    jython resources
    Installing a Library of Jython ScriptsPart of the WebSphere Application Server v7.x Administration Series Series
    jython好资料
    ulipad install on 64bit win7 has issue
    an oracle article in high level to descibe how to archtichre operator JAVA relevet project
    table的宽度,单元格内换行问题
    Linux常用命令大全
    dedecms系统后台登陆提示用户名密码不存在
    登录织梦后台提示用户名不存在的解决方法介绍
    Shell常用命令整理
  • 原文地址:https://www.cnblogs.com/nimo97/p/9724979.html
Copyright © 2011-2022 走看看