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. ...
随机推荐
- Python爬虫框架--pyspider初体验
之前接触scrapy本来是想也许scrapy能够让我的爬虫更快,但是也许是我没有掌握scrapy的要领,所以爬虫运行起来并没有我想象的那么快,看这篇文章就是之前使用scrapy的写得爬虫.然后昨天我又 ...
- ef6 code first with Oracle 试玩记录
对于oracle 使用code first 这边文章不错: http://www.cnblogs.com/wlflovenet/p/4187455.html 补充一下: 文章中提到machine.co ...
- hdu6000 Wash 巧妙地贪心
/** 题目:hdu6000 Wash 巧妙地贪心 链接:https://vjudge.net/contest/173364#problem/B 转自:http://blog.csdn.net/ove ...
- 【Raspberry Pi】修改时区
Raspberry Pi没有时钟模块,所以每次断电都会丢失时间,但它有联网获取时间的预设.但要修改默认时区 http://outofmemory.cn/code-snippet/2899/shumei ...
- hdu 4294(bfs)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4294 思路:题目的意思是说,给你n,k,则求出n的正整数倍数,使得这个数字在k进制下表示的时候需要的不 ...
- IOS . -转载-10行代码搞定九宫格
//每个Item宽高 CGFloat W = ; CGFloat H = ; //每行列数 NSInteger rank = ; //每列间距 CGFloat rankMargin = (self.v ...
- svn服务器配置 for mac
本文转载至 http://blog.sina.com.cn/s/blog_5e42f31a010156z4.html 1.找到合适的目录,新建一个版本库的目录:mkdir svn 创建版本库:sv ...
- Android UI开发第三十九篇——Tab界面实现汇总及比较
Tab布局是iOS的经典布局,Android应用中也有大量应用,前面也写过Android中TAb的实现,<Android UI开发第十八篇——ActivityGroup实现tab功能>.这 ...
- 做好准备,让你的短信应用迎接Android 4.4(KitKat)
Android团队通过Android开发博客透漏今年会放出Android 4.4 (KitKat) ,同时更新了 SMS 的部分API.博客上讲只有default SMS app才能对短信数据库有写权 ...
- delphi xe----操作mongoDB驱动,TMongoWire(Delphi MongoDB Driver)
所有例子来自:https://github.com/stijnsanders/TMongoWire Delphi MongoDB的驱动 一个Delphi的驱动程序来访问mongoDB的服务器.用jso ...