当前位置: 移动技术网 > IT编程>脚本编程>Python > python静态方法实例

python静态方法实例

2019年03月23日  | 移动技术网IT编程  | 我要评论

哈里发王国传奇,雨在风中吉他谱,wmsyspr9.prx

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网