How to define a static method in Python?
Demo:

#!/usr/bin/python2.7
#coding:utf-8
# FileName: test.py
# Author: lxw
# Date: 2015-07-03 #Inside a class, we can define attributes and methods
class Robot:
'''Robot class. Attributes and Methods'''
population = 0
def __init__(self, name):
self.name = name
Robot.population += 1
print('(Initialize {0})'.format(self.name)) def __del__(self):
Robot.population -= 1
if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots working.'.format(Robot.population)) def sayHi(self):
print('Greetings, my master call me {0}.'.format(self.name)) '''
#The following class method is OK.
@classmethod
def howMany(cls): #cls is essential.
print('We have {0:d} robots.'.format(cls.population))
''' '''
#The following static method is OK.
@staticmethod
def howMany():
print('We have {0:d} robots.'.format(Robot.population))
''' #The following class method is OK.
def howMany(cls): #cls is essential.
print('We have {0:d} robots.'.format(cls.population))
howMany = classmethod(howMany) '''
#The following static method is OK.
def howMany():
print('We have {0:d} robots.'.format(Robot.population))
howMany = staticmethod(howMany)
''' def main():
robot1 = Robot("lxw1")
robot1.sayHi()
#staticmethod/classmethod 都既可以使用类名访问,也可以使用对象名访问, 但classmethod在定义时需要cls参数
Robot.howMany()
robot1.howMany() robot2 = Robot("lxw2")
robot2.sayHi()
Robot.howMany()
robot2.howMany() if __name__ == '__main__':
main()
else:
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. 1.2 Activity

    Activity是个应用组件,它给用户提供了为了完成某些工作而可以进行交互操作的界面,例如,电话详情,打电 话,发邮件,或是浏览地图.每一个Activity都有一个窗口来绘制自已的用户界面.通常来说, ...

  2. HTML转义工具 [Javascript版]

    有时候需要在HTML中显示一些带有特殊字符的文本( < > & 空格) ,这时候就要用到HTML转义. 有了这个工具在博客发布HTML代码的时候就很方便了. <!DOCTYP ...

  3. android studio 中配置androidAnnotation 的新版正确配置

    apply ].processResources.manifestFile resourcePackageName 'com.peiandsky.firstandroidstudio' }}

  4. 页面表单里的图片上传ENCTYPE="multipart/form-data"

    ENCTYPE="multipart/form-data"用于表单里有图片上传. <form action="<%=basePath %>asyUplo ...

  5. Ubuntu14.04中安装Sublime_Text_3

    Sublime Text 简介 Sublime Text 是一款流行的文本编辑器软件,有点类似于TextMate,跨平台,可运行在Linux.Windows和Mac OS X.也是许多程序员喜欢使用的 ...

  6. 【Raspberry Pi】读取DHT11温度湿度波折

    从网上找到了DHT11厂家说明书,尝试用python根据时序图写数据获取驱动,但发现python的高层特性导致在做底层代码时例如控制20us时延这类需求就没什么好的办法. 还是得回到C-wiringP ...

  7. 在系统重装后为什么ChemDraw用不了

    作为一款非常受欢迎的化学绘图软件ChemDraw需要在满足运行条件的电脑上运行,但是一些用户发现自己在给自己的电脑重装系统之后,ChemDraw运行不了呢.导致ChemDraw用不了的原因比较多样,不 ...

  8. java项目学习

    GitHub地址:https://github.com/zhanglei-workspace/shopping-management-system

  9. npm安装express 公司上网设置代理

    异常: 0 info it worked if it ends with ok1 verbose cli [ 'C:\\Program Files (x86)\\nodejs\\\\node.exe' ...

  10. .net webapi项目跨域问题及解决方案

    问题: 1.项目完成,部署到不同的iis版本上,跨域访问有的通有的不通 解决办法: 1.将复杂请求改为简单请求 2.代码中去掉所有跨域设置,配置中添加或修改节点 <system.webServe ...