How to define a static method in Python?
Demo:

  1. #!/usr/bin/python2.7
  2. #coding:utf-8
  3. # FileName: test.py
  4. # Author: lxw
  5. # Date: 2015-07-03
  6.  
  7. #Inside a class, we can define attributes and methods
  8. class Robot:
  9. '''Robot class.
  10.  
  11. Attributes and Methods'''
  12. population = 0
  13. def __init__(self, name):
  14. self.name = name
  15. Robot.population += 1
  16. print('(Initialize {0})'.format(self.name))
  17.  
  18. def __del__(self):
  19. Robot.population -= 1
  20. if Robot.population == 0:
  21. print('{0} was the last one.'.format(self.name))
  22. else:
  23. print('There are still {0:d} robots working.'.format(Robot.population))
  24.  
  25. def sayHi(self):
  26. print('Greetings, my master call me {0}.'.format(self.name))
  27.  
  28. '''
  29. #The following class method is OK.
  30. @classmethod
  31. def howMany(cls): #cls is essential.
  32. print('We have {0:d} robots.'.format(cls.population))
  33. '''
  34.  
  35. '''
  36. #The following static method is OK.
  37. @staticmethod
  38. def howMany():
  39. print('We have {0:d} robots.'.format(Robot.population))
  40. '''
  41.  
  42. #The following class method is OK.
  43. def howMany(cls): #cls is essential.
  44. print('We have {0:d} robots.'.format(cls.population))
  45. howMany = classmethod(howMany)
  46.  
  47. '''
  48. #The following static method is OK.
  49. def howMany():
  50. print('We have {0:d} robots.'.format(Robot.population))
  51. howMany = staticmethod(howMany)
  52. '''
  53.  
  54. def main():
  55. robot1 = Robot("lxw1")
  56. robot1.sayHi()
  57. #staticmethod/classmethod 都既可以使用类名访问,也可以使用对象名访问, 但classmethod在定义时需要cls参数
  58. Robot.howMany()
  59. robot1.howMany()
  60.  
  61. robot2 = Robot("lxw2")
  62. robot2.sayHi()
  63. Robot.howMany()
  64. robot2.howMany()
  65.  
  66. if __name__ == '__main__':
  67. main()
  68. else:
  69. print("Being imported as a module.")

Differences between staticmethod and classmethod:

classmethod:

Its definition is mutable via inheritance, Its definition follows subclass, not parent class, via inheritance, can be

overridden by subclass. It is important when you want to write a factory method and by this custom attribute(s)

can be attached in a class.

staticmethod:

Its definition is immutable via inheritance. 类似其他语言中的static方法。

Python Static Method的更多相关文章

  1. Python OOP(2)-static method,class method and instance method

    静态方法(Static Method): 一种简单函数,符合以下要求: 1.嵌套在类中. 2.没有self参数. 特点: 1.类调用.实例调用,静态方法都不会接受自动的self参数. 2.会记录所有实 ...

  2. java.lang.NoSuchMethodError: No static method setLayoutDirection(Landroid/graphics/drawable/Drawable;I)V in class Landroid/support/v4/graphics/drawable/DrawableCompat

    Bug: java.lang.NoSuchMethodError: No static method setLayoutDirection(Landroid/graphics/drawable/Dra ...

  3. java.lang.NoSuchMethodError: No static method getFont

    最近在Android Studio升级3.0后,在AlertDialog弹窗时报出了如下问题: java.lang.NoSuchMethodError: No static method getFon ...

  4. When to use static method in a java class

    First , please understand its feature : * no need to instantiate a instance, i.e. simply you can jus ...

  5. How to call getClass() from a static method in Java?

    刚才在学习Java 使用properties类,遇到这样的错误: Cannot make a static reference to the non-static method getClass() ...

  6. 【转】 Java虚拟机内存的堆区(heap),栈区(stack)和静态区(static/method)

    JAVA的JVM的内存可分为3个区:堆(heap).栈(stack)和方法区(method) 堆区:1.存储的全部是对象,每个对象都包含一个与之对应的class的信息.(class的目的是得到操作指令 ...

  7. python dataframe (method,partial,dir,hasattr,setattr,getarrt)

    # * _*_ coding:utf-8 _*___author__:'denny 20170730'from functools import reduceimport functoolsimpor ...

  8. python logging method 02

    基本用法 下面的代码展示了logging最基本的用法.     1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...

  9. python string method

    嗯,学习其它语言没这样全练过,嘻嘻 //test.py 1 # -*- coding: UTF-8 -*- 2 3 str = "i am worker" 4 print str. ...

随机推荐

  1. Python爬虫框架--pyspider初体验

    之前接触scrapy本来是想也许scrapy能够让我的爬虫更快,但是也许是我没有掌握scrapy的要领,所以爬虫运行起来并没有我想象的那么快,看这篇文章就是之前使用scrapy的写得爬虫.然后昨天我又 ...

  2. ef6 code first with Oracle 试玩记录

    对于oracle 使用code first 这边文章不错: http://www.cnblogs.com/wlflovenet/p/4187455.html 补充一下: 文章中提到machine.co ...

  3. hdu6000 Wash 巧妙地贪心

    /** 题目:hdu6000 Wash 巧妙地贪心 链接:https://vjudge.net/contest/173364#problem/B 转自:http://blog.csdn.net/ove ...

  4. 【Raspberry Pi】修改时区

    Raspberry Pi没有时钟模块,所以每次断电都会丢失时间,但它有联网获取时间的预设.但要修改默认时区 http://outofmemory.cn/code-snippet/2899/shumei ...

  5. hdu 4294(bfs)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4294 思路:题目的意思是说,给你n,k,则求出n的正整数倍数,使得这个数字在k进制下表示的时候需要的不 ...

  6. IOS . -转载-10行代码搞定九宫格

    //每个Item宽高 CGFloat W = ; CGFloat H = ; //每行列数 NSInteger rank = ; //每列间距 CGFloat rankMargin = (self.v ...

  7. svn服务器配置 for mac

      本文转载至 http://blog.sina.com.cn/s/blog_5e42f31a010156z4.html 1.找到合适的目录,新建一个版本库的目录:mkdir svn 创建版本库:sv ...

  8. Android UI开发第三十九篇——Tab界面实现汇总及比较

    Tab布局是iOS的经典布局,Android应用中也有大量应用,前面也写过Android中TAb的实现,<Android UI开发第十八篇——ActivityGroup实现tab功能>.这 ...

  9. 做好准备,让你的短信应用迎接Android 4.4(KitKat)

    Android团队通过Android开发博客透漏今年会放出Android 4.4 (KitKat) ,同时更新了 SMS 的部分API.博客上讲只有default SMS app才能对短信数据库有写权 ...

  10. delphi xe----操作mongoDB驱动,TMongoWire(Delphi MongoDB Driver)

    所有例子来自:https://github.com/stijnsanders/TMongoWire Delphi MongoDB的驱动 一个Delphi的驱动程序来访问mongoDB的服务器.用jso ...