python静态方法实例

yipeiwu_com5年前Python基础

本文实例讲述了python静态方法。分享给大家供大家参考。

具体实现方法如下:

复制代码 代码如下:
staticmethod Found at: __builtin__
staticmethod(function) -> method
    
    Convert a function to be a static method.
    
    A static method does not receive an implicit first argument.
    To declare a static method, use this idiom:
    
    class C:
    def f(arg1, arg2, ...): ...
    f = staticmethod(f)
    
    It can be called either on the class (e.g. C.f()) or on an
     instance
    (e.g. C().f()).  The instance is ignored except for its class.
    
    Static methods in Python are similar to those found in
     Java or C++.
    For a more advanced concept, see the classmethod builtin.
  
class Employee:
   """Employee class with static method isCrowded"""
 
   numberOfEmployees = 0  # number of Employees created
   maxEmployees = 10  # maximum number of comfortable employees
 
   def isCrowded():
      """Static method returns true if the employees are crowded"""
 
      return Employee.numberOfEmployees > Employee.maxEmployees
 
   # create static method
   isCrowded = staticmethod(isCrowded)
 
   def __init__(self, firstName, lastName):
      """Employee constructor, takes first name and last name"""
 
      self.first = firstName
      self.last = lastName
      Employee.numberOfEmployees += 1
 
   def __del__(self):
      """Employee destructor"""
 
      Employee.numberOfEmployees -= 1    
 
   def __str__(self):
      """String representation of Employee"""
 
      return "%s %s" % (self.first, self.last)
 
# main program
def main():
   answers = [ "No", "Yes" ]  # responses to isCrowded
   
   employeeList = []  # list of objects of class Employee
 
   # call static method using class
   print "Employees are crowded?",
   print answers[ Employee.isCrowded() ]
 
   print "\nCreating 11 objects of class Employee..."
 
   # create 11 objects of class Employee
   for i in range(11):
      employeeList.append(Employee("John", "Doe" + str(i)))
 
      # call static method using object
      print "Employees are crowded?",
      print answers[ employeeList[ i ].isCrowded() ]
 
   print "\nRemoving one employee..."
   del employeeList[ 0 ]
 
   print "Employees are crowded?", answers[ Employee.isCrowded() ]
 
if __name__ == "__main__":
   main()

希望本文所述对大家的Python程序设计有所帮助。

相关文章

window环境pip切换国内源(pip安装异常缓慢的问题)

在使用pip默认的安装源时,安装速度通常会比较缓慢。通过切换为国内的安装源通常会解决这个问题,以下是解决步骤: 在如下目录新增一个pip文件 \Users\Administrato...

Python动态加载模块的3种方法

1、使用系统函数__import_() 复制代码 代码如下: stringmodule = __import__('string') 2、使用imp 模块 复制代码 代码如下: imp...

python基础while循环及if判断的实例讲解

wlile循环 while True表示永远为真,不管是什么条件都会向下执行,下面是写的一个例子。 #!/usr/bin/env python age = 24           ...

python实现转圈打印矩阵

本文实例为大家分享了python实现转圈打印矩阵的具体代码,供大家参考,具体内容如下 #! conding:utf-8 __author__ = "hotpot" __date__...

window下eclipse安装python插件教程

window下eclipse安装python插件教程

本教程为大家分享了eclipse安装python插件的具体步骤,供大家参考,具体内容如下 1.安装python环境 python安装包下载地址:https://www.python.or...