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程序设计有所帮助。

相关文章

利用Tkinter和matplotlib两种方式画饼状图的实例

当我们学习python的时候,总会用到一些常用的模块,接下来我就详细讲解下利用两种不同的方式画饼状图。 首先利用【Tkinter】中的canvas画布来画饼状图: from tkin...

老生常谈python的私有公有属性(必看篇)

python中,类内方法外的变量叫属性,类内方法内的变量叫字段。他们的私有公有访问方法类似。 class C: __name="私有属性" def func(self):...

Python中文件遍历的两种方法

关于Python的文件遍历,大概有两种方法,一种是较为便利的os.walk(),还有一种是利用os.listdir()递归遍历。 方法一:利用os.walk os.walk可以自顶向下或...

Python GUI学习之登录系统界面篇

Python GUI学习之登录系统界面篇

导言篇: 我的python环境是:python3.6.5 这里我选择的GUI编程包是:tkinter tkinker在python2.5以后就是自带包了,所以我们不需要另外安装 tkin...

Python实现一个简单的验证码程序

  老师讲完random函数,自己写的,虽然和老师示例的不那么美观,智能,但是也自己想出来的,所以记录一下,代码就需要自己不断的自己练习,实战,才能提高啊!不然就像我们这些大部分靠自学的...