python静态方法实例

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

相关文章

Python探索之ModelForm代码详解

这是一个神奇的组件,通过名字我们可以看出来,这个组件的功能就是把model和form组合起来,对,你没猜错,相信自己的英语水平。 先来一个简单的例子来看一下这个东西怎么用: 比如我们...

python生成器generator用法实例分析

本文实例讲述了python生成器generator用法。分享给大家供大家参考。具体如下: 使用yield,可以让函数生成一个结果序列,而不仅仅是一个值 例如: def countdo...

在Python中使用mechanize模块模拟浏览器功能

知道如何快速在命令行或者python脚本中实例化一个浏览器通常是非常有用的。 每次我需要做任何关于web的自动任务时,我都使用这段python代码去模拟一个浏览器。  ...

python3在同一行内输入n个数并用列表保存的例子

最近在学习算法,经常遇到一行有多个数据,用空格或者','进行分割。最开始不懂,直接百度, n = input() n = int(n) list1 = [] list1 = inpu...

Python中url标签使用知识点总结

Python中url标签使用知识点总结

1.在模板中,我们经常要使用一些url,实现页面之间的跳转,比如某个a标签中需要定义href属性。当然如果通过硬编码的方式直接将这个url固定在里面也是可以的,但是这样的话,对于以后进行...