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. ...
随机推荐
- MapReduce实战(五)实现关联查询
需求: 利用MapReduce程序,实现SQL语句中的join关联查询. 订单数据表order: id date pid amount 1001 20150710 P0001 2 1002 20150 ...
- 玩转Win10的45个快捷键
1Win10快捷键大全(第一部分) Win10发布已经快两个星期了,各项新功能也让小伙伴们兴奋不已.和之前系统一样,Win10也加入了很多经典的快捷键,同时还加入了全新触控手势.今天小编就将所有的Wi ...
- 微信小程序2 - 扩展Page参数
官方默认的Page初始代码为 var option = { /** * 页面的初始数据 */ data: { }, /** * 生命周期函数--监听页面加载 * */ onLoad: function ...
- css3动画4
效果: 代码: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head&g ...
- php+mysqli实现批量执行插入、更新及删除数据的方法
本文实例讲述了php+mysqli实现批量执行插入.更新及删除数据的方法.分享给大家供大家参考.具体如下: mysqli批量执行插入/更新/删除数据,函数为 multi_query(). 下面的代码只 ...
- 要创建一个EJB,必须要至少编写哪些Java类和接口?
要创建一个EJB,必须要至少编写哪些Java类和接口? A. 定义远程(或业务)接口 B. 定义本地接口 C. 定义Bean接口 D. 编写Bean的实现 解答:ABC
- <!>贴图/音乐
<img src=图片位址>贴图 <img src=图片位址 width=’180’>设定图片宽度 <img src=图片位址 height=’30’>设定图片高度 ...
- 【python】计算器
from __future__ import division import sys from math import * from PyQt4.QtCore import * from PyQt4. ...
- 好久没写blog了 ~ 换了个城市,换了个公司,各种忙碌
最近一直在忙工作交接以及换城市.入职的事情 ~~~ 新公司做C++的比较少,so全上C++11了,写代码各种爽. 最近应该会写一点关于QT的blog , 学到新知识了哈.
- Docker入门与应用系列(五)Dockerfile
Dockerfile是为快速构建docker image而设计的,当你使用dockerbuild 命令的时候,docker 会读取当前目录下的命名为Dockerfile(首字母大写)的纯文本文件并执行 ...