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. ...
随机推荐
- [J2EE]MyBatis HelloWorld
一.MyBatis简单介绍 iBatis是apche的一个开源项目.2010年迁移到google code后改名为MyBatis,2013年前已到github.MyBatis是一个基于java的持久层 ...
- [转]Python定时任务框架APScheduler
APScheduler是基于Quartz的 一个Python定时任务框架,实现了Quartz的所有功能,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以 持久化任务 ...
- 用C/C++扩展你的PHP 为你的php增加功能
英文版下载: PHP 5 Power Programming http://www.jb51.net/books/61020.html PHP取得成功的一个主要原因之一是她拥有大量的可用扩展.web开 ...
- linux远程控制windows
我的开发环境是linux,但是需要同时维护windows和linux的服务器,所以有时需要在linux系统下也能远程控制windows的机器. rdesktop是一款开源的远程连接工具,它通过实现了R ...
- 什么是 AJAX ?
什么是 AJAX ? AJAX = 异步 JavaScript 和 XML. AJAX 是一种用于创建快速动态网页的技术. 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新.这意味 ...
- ACM/ICPC Moscow Prefinal 2019 趣题记录
### Day1: ### **Problem C:** 设$k_i$为$[A, B]$中二进制第$i$位是1的数的个数. 给出$k_0 \cdots k_{63}$, 求出$[A, B]$ ...
- (转)java 静态内部类
转自:http://blog.sina.com.cn/s/blog_605f5b4f0100zbps.html 参考:http://docs.oracle.com/javase/tutorial/ja ...
- 【转】SetThreadLocale解决越南文乱码问题
转自http://hi.baidu.com/killwolf110/item/838d56224067c63395f62b70 程序需要运行在越南地区,语言为越南文,操作系统为英文版,程序支持unic ...
- 【Python】GUI 练习1--利率计算器
import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class Form(QDialog): def __init__(se ...
- C# 各版本的新特性
http://www.cnblogs.com/JeffreySun/archive/2012/11/14/2770211.html