Python Static Method
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的更多相关文章
- Python OOP(2)-static method,class method and instance method
静态方法(Static Method): 一种简单函数,符合以下要求: 1.嵌套在类中. 2.没有self参数. 特点: 1.类调用.实例调用,静态方法都不会接受自动的self参数. 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 ...
- java.lang.NoSuchMethodError: No static method getFont
最近在Android Studio升级3.0后,在AlertDialog弹窗时报出了如下问题: java.lang.NoSuchMethodError: No static method getFon ...
- 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 ...
- How to call getClass() from a static method in Java?
刚才在学习Java 使用properties类,遇到这样的错误: Cannot make a static reference to the non-static method getClass() ...
- 【转】 Java虚拟机内存的堆区(heap),栈区(stack)和静态区(static/method)
JAVA的JVM的内存可分为3个区:堆(heap).栈(stack)和方法区(method) 堆区:1.存储的全部是对象,每个对象都包含一个与之对应的class的信息.(class的目的是得到操作指令 ...
- python dataframe (method,partial,dir,hasattr,setattr,getarrt)
# * _*_ coding:utf-8 _*___author__:'denny 20170730'from functools import reduceimport functoolsimpor ...
- 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 ...
- python string method
嗯,学习其它语言没这样全练过,嘻嘻 //test.py 1 # -*- coding: UTF-8 -*- 2 3 str = "i am worker" 4 print str. ...
随机推荐
- MongoDB的容量规划及硬件配置
mongo是基于内存的数据库,应尽量将工作集中的数据全部加载到内存中,即内存应大于工作集 本文译自Chad Tindel的英文博客: http://www.mongodb.com/blog/post/ ...
- 重载(Overload)
重载(Overload) 重载(overloading) 是在一个类里面,方法名字相同,而参数不同.返回类型可以相同也可以不同. 每个重载的方法(或者构造函数)都必须有一个独一无二的参数类型列表. 最 ...
- 嵌入式驱动开发之dsp fpga通信接口---spi串行外围接口、emif sram接口
-----------------------------------------author:pkf ------------------------------------------------ ...
- 使用JSR验证
1.spring mvc配置文件中添加: <mvc:annotation-driven /> 2.pom.xml中添加 <dependency > ...
- openwrt U盘启动
参考链接: http://m.blog.csdn.net/blog/zcynical/44892785
- 《C语言及程序设计》实践參考——分数的累加
返回:贺老师课程教学链接 项目要求 [项目1:分数的累加]编程序.输出1/3-3/5+5/7-7/9-+19/21的结果提示:假设直接解决上面的问题有困难.能够设计一条"由易到难" ...
- VC++调节显示器的亮度SetDeviceGammaRamp
出处:http://www.nirsoft.net/vc/change_screen_brightness.html SetDeviceGammaRamp API函数位于Gdi32.ll中,接收一个2 ...
- java 连接mariadb 无法获取数据源的问题,在ubuntu上部署的时候(原创)
问题: 连接数据库时报错: log4j:WARN No appenders could be found for logger (com.mchange.v2.log.MLog).log4j:WARN ...
- Linux查看网络和IO性能问题
Linux上使用iftop可以查看网络使用情况,使用iotop可以查看磁盘io使用情况 首先需要安装iftop和iotop: yum install iftop yum install iotop = ...
- OSX终端 命令行的一些基本操作
本文转载至 http://blog.csdn.net/xdrt81y/article/details/24058959 osx终端命令 OSX终端 命令行的一些基本操作终端 命令行的一些基本操作很多朋 ...