欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python静态方法实例

程序员文章站 2023-11-20 12:59:34
本文实例讲述了python静态方法。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下:staticmethod found at: __builtin__...

本文实例讲述了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程序设计有所帮助。